tags:

views:

236

answers:

3

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

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

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)

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

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

elder_george
you may want to mention the Type.IsAssignableFrom method: http://msdn.microsoft.com/en-us/library/system.type.isassignablefrom.aspx
Simon
@Simon thank you for this note. I really should mention it.
elder_george
+1  A: 

Have a look at reflection (http://msdn.microsoft.com/de-de/library/ms173183%28VS.80%29.aspx).

For example, your code would be:

Type refClass = refChildNode.GetType();
Type testClass = testChildNode.GetType();
if (refClass != testClass) 
{
    ....
}
Maximilian Mayerl
+1  A: 

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.

RaceFace