Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if object instantiated

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.
like image 826
Dave Avatar asked Feb 01 '13 14:02

Dave


People also ask

How do you check if an object is instantiated?

If you want to see if an object has ever been instantiated, you'd need to modify that object's class to provide some type of private static bool (or counter) that gets flagged when an object is constructed. This would let you track how often it's being created directly.

How can we check if an object was instantiated from a particular class?

The instanceof operator allows to check whether an object belongs to a certain class. It also takes inheritance into account.


1 Answers

if (saveBundleResponse != null)
{
    var header = saveBundleResponse.Header;
    if (header != null)
    {
        var status = header.Status;
    }
}
like image 154
Sergey Berezovskiy Avatar answered Sep 28 '22 04:09

Sergey Berezovskiy