Question

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).

Was it helpful?

Solution

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.

OTHER TIPS

You probably have a name conflict with another 'Service' (class or namespace). The use of this solves it.

I'm a bit skeptical about the difference between Cassinin and IIS, have you carefully checked that?

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)

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.

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top