tags:

views:

51

answers:

3

In C# using VS2005, if I have a variable of type Object, to which I assign a MyObjectType object by casting as follows:

MyObjectType myObj = GetMyObject();
Object obj = (Object)myObj;

Is there way to determine that obj is actually a MyObjectType and not just an Object?

+2  A: 

Absolutely:

if (obj is MyObjectType)
{
    ...
}

Or, if you want to then use some members of it:

MyObjectType mot = obj as MyObjectType;
if (mot != null)
{
    ...
}

Note that these will work even if obj refers to an object derived from MyObjectType. If you only want an exact match, you should use:

if (obj != null && obj.GetType() == typeof(MyObjectType))

... but that's a pretty rare use case in my experience.

Jon Skeet
@John: but isn't obj an Object and not an MyObjectType?
Craig Johnston
@Craig: No, you assigned a `MyObjectType` to it, so it’s a `MyObjectType`, even if it’s stored in a variable of type `object`.
Timwi
@Craig: `obj` is a variable, not an object at all. The *value* of `obj` isn't an object either - it's a reference. It may be a reference to an instance of `Object`, or to an instance of `MyObjectType`, or some other type... or null. Note that the type of an object itself never changes, even if you store a reference to it in a different type of variable.
Jon Skeet
@John: if I want to use some members of it, can I cast and then refer to a member all in the one line?
Craig Johnston
@Craig: You can cast and then use the result directly, but it will throw an exception if the object isn't of the right type. You'd write `((MyObjectType)obj).SomeMember()`
Jon Skeet
@Jon: is the (obj is MyObjectType) style of expression an acceptable way to perform some programming logic within a program? Or is there a danger that something could go wrong? Does this have anything to do with Reflection?
Craig Johnston
@Craig: Usually you *do* want to use the object afterwards, so the second form is simpler. I'm not sure what kind of "danger" you're thinking about. It doesn't really have anything to do with reflection, as such.
Jon Skeet
+1  A: 
if (obj is MyObjectType)
vc 74
Mr Skeet, you're too fast...
vc 74
A: 

If you want to check if obj is a MuObjectType you can write

if( obj is MyObjectType)

This returns true if obj is infact a MyObjectType, else false.

Øyvind Bråthen