Looking for a base class with typeof?
-
I have a case where several objects may trigger an event that is handled in one place. I use the sender object type to determine whether I should perform some task on the object. However, how can I catch the condition where an object inherits from the type of object I am interested in? I'd like to include that object as well. Here is an example of what I am doing:
if (sender.GetType() == typeof(CMyClass) ) { //Do Something }
If something is derived from CMyClass, I'd like it to go through the "Do Something" code. How can I check for it? -
I have a case where several objects may trigger an event that is handled in one place. I use the sender object type to determine whether I should perform some task on the object. However, how can I catch the condition where an object inherits from the type of object I am interested in? I'd like to include that object as well. Here is an example of what I am doing:
if (sender.GetType() == typeof(CMyClass) ) { //Do Something }
If something is derived from CMyClass, I'd like it to go through the "Do Something" code. How can I check for it?Just test if you can cast it to the other class/interface:
if (sender as CMyClass != null)
{
//Do Something
} -
I have a case where several objects may trigger an event that is handled in one place. I use the sender object type to determine whether I should perform some task on the object. However, how can I catch the condition where an object inherits from the type of object I am interested in? I'd like to include that object as well. Here is an example of what I am doing:
if (sender.GetType() == typeof(CMyClass) ) { //Do Something }
If something is derived from CMyClass, I'd like it to go through the "Do Something" code. How can I check for it? -
Just test if you can cast it to the other class/interface:
if (sender as CMyClass != null)
{
//Do Something
}Ah, thanks! That is what I wanted. In case anyone else is interested, another way to handle this issue (or get around it) is by associating your base class with an interface. All inherited classes are also of the same interface so I was able to do something like this:
if (sender is ISomeInterface)
{
// Do Something
} -
Use the
is
keyword:if (sender is CMyClass) { //Do Something }
--- b { font-weight: normal; }Ah! This is what I want. Thanks.