I have a strange bug in a multithreaded app:
public class MyClass
{
private readonly Hashtable HashPrefs;
public MyClass(int id)
{
HashPrefs = new Hashtable();
}
public void SomeMethodCalledFromAnotherThread(string hashKey,string hashValue)
{
if (HashPrefs.Contains(hashKey)) // <-- throws NullReferenceException
{
}
}
}
One thread does the :
SomeQueue.Add(new MyClass(1));
And another thread does the :
SomeQueue.Dequeue().SomeMethodCalledFromAnotherThread(SomeClass.SomeMethod(),"const value");
But how can the second thread call the method before the constructor is finished?
Edit: I added the part with the function parameters, as it seems this might be relevant.
As far as I can tell, the hashKey being passed on cannot be null, as SomeMethod() always returns a relevant string.
As others have pointed out,if the problem was a null haskKey parameter passed to the Contains() , the exception would be ArgumentNullException.
Reflection is one way to do this (
SetField).A second way to get this curiosity is if you give away the reference too early, by passing
this(or sometihng involving an implicitthis, such as a field captured into an anonymous method / lambda) out of the.ctor:Or more likely (given the question):
Another relevant question might be – can it not be assigned in the first place? And the answer to that is yes, especially if you are using serialization. Contrary to popular belief, you can actually bypass the constructors, if you have a reason;
DataContractSerializeris a good example of something that does this…The following will create a
MyClasswith a null field: