I will start by explaining my scenario in code:
public class A { }
public class B : A { }
public class C : B { }
public class D { }
public c
For VB.NET with Visual Studio 2008, you can check it like:
'MyTextBox control is inherited by Textbox
If Ctl.GetType.Name = "MyTextBox" then
End If
As an alternative to the (c is B)
check, you can also do the following:
var maybeB = c as B;
if (maybeB != null) {
// make use of maybeB
}
This is preferred in some cases since in order to make use of c
as a B
when using is
, you would have to cast anyway.
You can just use is
:
if (c is B) // Will be true
if (d is B) // Will be false
This looks like a job for polymorphism, as opposed to a big switch statement with tests for specific classes.
typeof(B).IsInstanceOfType(c)
Similar to the answer above from sam-harwell, sometimes you may have the type "B" in a variable, so you need to use reflection rather than the "is" operator.
I used Sam's solution, and was pleasantly surprised when Resharper made this suggestion.
Edit: this answers the question in the thread title. cdm9002 has the better answer to the problem as described in the full post.
typeof(B).IsAssignableFrom(c.GetType())