Reputation: 5286
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 (rather ugly) solution:
Type sourceT = MyBindingSource.DataSource.GetType();
if( sourceT == null || sourceT.ToString().Equals("System.RuntimeType") ) {
return null;
}
return (ExpectedObjType) result;
The System.RuntimeType
is private and non-accessible, so I can't do this:
Type sourceT = MyBindingSource.DataSource.GetType();
if ( object.ReferenceEquals(sourceT, typeof(System.RuntimeType)) ) {
return null;
}
return (ExpectedObjType) result;
I was just wondering if a better solution exists? Particularly one that doesn't rely on the Type
name.
Upvotes: 3
Views: 1832
Reputation: 33089
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.
Upvotes: 1
Reputation: 71563
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".
Upvotes: 1