Compare class names of interface inherited classes

G

Guest

Let's say I have this:

interface MyInterface {}
class MyClass1 : MyInterface {...}
class MyClass2 : MyInterface {...}

class SomeClass
{
MyInterface myClassX;
public SomeFunc()
{
if (someCondition)
myClassX = new MyClass1();
else
myClassX = new MyClass2();
}

public AnotherFunc()
{
/*Here I want to see which class the myClassX variable belongs to. How
to do that? */
}
}
 
B

Barry Kelly

MyInterface myClassX;
public AnotherFunc()
{
/*Here I want to see which class the myClassX variable belongs to. How
to do that? */

myClassX.GetType() returns a Type instance.

You can get the Type instance corresponding to a C# type with the
typeof operator, for example "typeof(MyClass1)".

However, if you need to check the type of the class implementing the
interface, you have bigger design problems. You probably need to add a
method to MyInterface which encapsulates what you're trying to do, and
call it directly, and then let polymorphism and selective
implementation in MyClass1 and MyClass2 decide the different
behaviour.

-- Barry
 
P

pradeep via DotNetMonster.com

You can write something similar to this as per your need

string x = myClassX is MyClass1 ? "Class 1" : "Class 2";
Console.WriteLine(x);

regards,
pradeep
 
I

Ignacio Machin \( .NET/ C# MVP \)

Hi,


What you want to do?

You use an interface to precisely avoid having to know what precise type
your instance is.
Also remember that any number of classes can implement the same interface,
what would happen if at a later time another person create a class that also
implement that interface, try to use your code (it does expect an interface
that the new class implement) and your code will not work as this new class
did not exist when you wrote your code?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top