Pratik
Pratik

Reputation: 161

How to find class of an object?

I have a method named A(Object senderObject) which receives senderObjectas parameter, which is nothing but object of sender. At runtime , I am not sure which class would call this method but what I need is not to just get from which class is it (Using getType) but also to cast it to its real class type and assign to another same class object.

Let me give you an example to clear my question. Suppose if the senderObject is from class A, I need to do:

A objAnother = (A)senderObject.

Suppose if the senderObject is from class B, I need to do:

B objAnother = (B)senderObject.

May I know how to do it? I need Dynamic method for the same.

Upvotes: 0

Views: 282

Answers (2)

bobbyalex
bobbyalex

Reputation: 2751

You can use the is keyword to do this.

if (senderObject is ClassA)
{
}

Upvotes: 0

Patrick Hofman
Patrick Hofman

Reputation: 157048

You can use is and as:

if (senderObject is A)
{
    // do something
}

Or:

A a = senderObject as A;

if (a != null)
{
    // do something
}

Upvotes: 2

Related Questions