Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the c# equivalents of of Java's getClass(), isAssignableFrom(), etc.?

Tags:

java

c#

class

I am translating from Java to C# and have code similar to:

Class<?> refClass = refChildNode.getClass();
Class<?> testClass = testChildNode.getClass();
if (!refClass.equals(testClass)) {
   // Do something
}

and elsewhere use Class.isAssignableFrom(Class c)... and similar methods

Is there a table of direct equivalents for class comparsion and properties and code-arounds where this isn't possible?

(The <?> is simply to stop warnings from the IDE about generics. A better solution would be appreciated)

like image 830
peter.murray.rust Avatar asked Oct 13 '09 08:10

peter.murray.rust


2 Answers

Type refClass = refChildNode.GetType();
Type testClass = testChildNode.GetType();
if (!refClass.Equals(testClass)) 
{
    ....
}

Have a look on System.Type class. It have methods you need.

like image 180
elder_george Avatar answered Oct 01 '22 07:10

elder_george


Firstly, to get the class (or in .NET speak, Type) you can use the following method:

Type t = refChildNode.GetType();

Now you have the Type, you can check equality or inheritance. Here is some sample code:

public class A {}

public class B : A {}

public static void Main()
{
    Console.WriteLine(typeof(A) == typeof(B));                 // false
    Console.WriteLine(typeof(A).IsAssignableFrom(typeof(B)));  // true
    Console.WriteLine(typeof(B).IsSubclassOf(typeof(A)));      // true
}

This uses the System.Reflection functionality. The full list of available methods is here.

like image 27
Dunc Avatar answered Oct 01 '22 09:10

Dunc