I was asked for more info: The original problem is below
I saw the answer I was pointed to above. I did look before posting. That is how I found .IsSubclassOf
which I didn't know existed (I am VERY new to C#
).
What I don't understand is why I am getting an error when I try to use the command.
I need to be able to tell if some object O is a sub-class of some other class C. It is okay if I specify the type of class C is directly (such as ListBox
) but what class O
is will vary, which is why I need to check. O might be one of many objects derived from ListBox
or it might be an object derived from TextBox
or it might be something else. I need to be able to act on those cases where a method is being passed objects that are derived from or sub-classes of ListBox or whatever class O may or may not be derived/sub-classed from
The example I give below would work fine if "st" could work in last statement. But it doesn't work. It gives me an error. I am told that I can not use a variable there--I have to use a Type. But the variable IS a type. I declare it as a type above. I can't name the type specifically because I will not know the type of the object. I have to get it with GetType
.
Original problem/post:
I need to be able to tell if an instance of an object is derived from a particular class.
This is just some example code to test the type of
and "is a IsSubclassOf"
methods, but they do not seem to work for me.
ListBox tb = new ListBox();
NoVerticalScrollCheckedListBox nvlb = new NoVerticalScrollCheckedListBox();
Type st = nvlb.GetType();
Type uType = tb.GetType();
bool b = typeof(st).IsSubclassOf(uType);
Console.Write("BOOL: " + b);
I get the error that I am trying to use variable st as a type, but st is a type. I can put in the actual class name such as "NoVerticalScrollCheckedListBox"
but that will not give me the information I want because what I want to be able to discover is if a particular object instance is derived from another class, not whether or not the class is derived from that other class abstractly.
I would like to make a method, for example, that would treat all objects derived from a ListBox in a particular way, regardless of whether it is one of several existing sub-types or of a new sub-type that may come along.