views:

101

answers:

4

Hi there,

I have the following code:

CustomerService service;
public CustomerService Service
{
    get
    {
        if (this.service == null)
        {
            this.service = new CustomerService();
        }
        return this.service;
    }
}

public DataTable GetCustomers()
{
    return this.Service.GetCustomers();
}

Now the question is: if I wrote the above method as follow (without "this"), it's giving me an error : instance is not reference to an object.

public DataTable GetCustomers()
{
    return Service.GetCustomers(); // this will spell the error "instance is not reference to an object"
}

Does anyone know? also it only happens while running via IIS and not from casini web server (VS 2010).

A: 

I fiddled a bit with your code in Visual Studio and I couldn’t even get a name conflict to produce the error message you described. I can’t think of any case in which “this.X” can ever be different from “X” except when “X” is a local variable or a method parameter.

Timwi
And did you also code-deploy that to IIS ?
Henk Holterman
+2  A: 

The presence or absence of this cannot explain the error you are witnessing. In this situation they mean exactly the same thing and will compile to the same IL code. Check the assembly using .NET Reflector to verify this if you wish. The error is occurring at random, probably due to a race condition.

One thing I can immediately see is that if you are running this code from multiple threads then it looks like you have a race condition here:

if (this.service == null)
{
    this.service = new CustomerService();
}
return this.service;

In the multithreaded case you would need to lock otherwise you could get two CustomerService objects. I'm not sure if this explains your error, but it certainly could create confusion. Race conditions can occur in one environment but not in another as the frequency of the error can depend on the type of the hardware and on what other processes are running on the server.

You may also have other race conditions in the code you haven't posted. Don't use this lazy initialization technique without locking unless you are sure that you have only one thread.

Mark Byers
not sure about this racing thingy but when I created the CustomerServiceClass object in the page_load event (used to be outside the page_load event) now it works ok..
A: 

Would the CustomerService class derive from a base class called Service? If so, then that's the problem.

Enigmativity
Nope, tried it — the property name hides the class.
Timwi
+1  A: 

Hello,

Something like this should be in a singleton. Which would resolve many issues like threading if implemented correctly and would make the implementation and readability of the code much better.

Thanks -Blake Niemyjski (.netTiers team member)

Blake Niemyjski