views:

53

answers:

2

I want to determine whether MyBindingSource.DataSource is assigned to the designer-set Type, or if it has been assigned an object instance. This is my current (somewhat ugly) solution:

object result = MyBindingSource.DataSource;
if(result.GetType().ToString() == "System.RuntimeType")
     return null;

return (ExpectedObjType) result;

The System.RuntimeType is private and non-accessible, so I can't do this:

if (object.ReferenceEquals(result.GetType(), typeof(System.RuntimeType)))
     return null;

return (ExpectedObjType) result;

I was just wondering if a better solution exists -- one that doesn't rely on converting the Type to a string?

+1  A: 

Since System.RuntimeType is derived from System.Type you should be able to do the following:

object result = MyBindingSource.DataSource;
if (typeof(Type).IsAssignableFrom(result.GetType()))
{
    return null;
}
return (ExpectedObjType)result;

or even more concisely:

object result = MyBindingSource.DataSource;
if (result is Type)
{
    return null;
}
return (ExpectedObjType)result;

Coincidentally this is the approach adopted here.

Richard Cook
Exactly what I was looking for, thanks!
Rob
A: 

You don't have to ToString() it; you should be able to access its Name through GetType() (which is pretty much the same thing). Either way, because it's a private class and not accessible from developer code, I think you're stuck with a "magic string" if you need to verify that it is specifically a RuntimeType. Not all "best solutions" are as elegant as we'd like.

If all Type parameters you'd get are actually RuntimeType objects, you can look for the base class as was suggested in another answer. However, if you can receive a Type that isn't a RuntimeType, you'll get some "false positives".

KeithS