Reputation: 8461
I have an object which is made of many other objects! I am trying to find the value of of one of the properties (an enum) but can't.
Now, normally if I want to check if an object is null I can do
if (object == null)
but this results in the same error.
I tried
if (object.Equals(null)) and the same error.
The error message I'm getting is objectName threw exception: System.NullReferenceException: Object reference not set to an instance of an object..
I'm trying to determine if my object is instantiated or not. Now, I can stick this into a try catch, if it errors then I know it's not, but to me this feels very wrong (although I may not have a choice).
The other problem I have is this project isn't mine and is a black box to everyone and so I can't make any changes to the original object! This means, all I have is what I have got, an object which may or may not be instantiated and I need a way of telling.
Other than the try catch, do I have any other options?
EDIT
So, the object is
public partial class SaveBundleResponse
{
SaveBundleResponseHeader header;
}
public partial class SaveBundleResponseHeader
{
private SaveBundleResponseHeaderStatus status;
}
public enum SaveBundleResponseHeaderStatus
{
Success, Fail, OK, OtherStates
}
So the SaveBundleResponse is created initially, the instance is then passed through a 'workflow' style environment and each property becomes 'populated/updated' etc as it goes deeper into the workflow. However, in a few situations, the enum is never set.
The problem is, I need to know the value of the enum (or if it is null).
The code I am trying to use is
if (saveBundleResponse.Header.Status // what ever happens, it fails at this point as Status is not initiated.
Upvotes: 12
Views: 26785
Reputation: 515
You should be able to use something like this:
SaveBundleResponse sbr = ...;
if (sbr.Header != null && !sbr.IsDisposed)
{
//Do the work
}
This should work (if the class is not a control you can't use the IsDisposed check).
Upvotes: 4
Reputation: 236218
if (saveBundleResponse != null)
{
var header = saveBundleResponse.Header;
if (header != null)
{
var status = header.Status;
}
}
Upvotes: 10