Reputation: 82301
Is there a way to get code like this print "Test";
DecendedTextBox myControl = new DecendedTextbox();
if (myControl is "TextBox")
{
Debug.WriteLine("Test");
}
The point here is that I need to see if myControl inherits from a type that I don't have a reference to at Compile Time.
Upvotes: 0
Views: 67
Reputation: 23208
If you need to avoid pulling the Type
reference out via reflection, then you can crawl up the inheritance tree:
public static bool IsTypeSubclassOf(Type subclass, string baseClassFullName)
{
while (subclass != typeof(object))
{
if (subclass.FullName == baseClassFullName)
return true;
else
subclass = subclass.BaseType;
}
return false;
}
Upvotes: 1
Reputation: 59367
If you don't have a reference to the type, you can do this:
DecendedTextBox myControl = new DecendedTextbox();
if (myControl.GetType().Name == "TextBox")
{
Debug.WriteLine("Test");
}
If you want to know the full type name, including namespace, you can use GetType().FullName
As far as checking to see if it inherits from the type, something like this:
DecendedTextBox myControl = new DecendedTextbox();
Type typeToCheck = Type.GetType("TextBox");
if (myControl.GetType().IsSubclassOf(typeToCheck))
{
Debug.WriteLine("Test");
}
Note that Type.GetType takes an AssemblyQualifiedName, so you'll need to know the full type name.
Upvotes: 1