Search code examples
c#asp.netiis.nettiers

what would make the "this" clause different?


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


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.