10

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)

1
  • 10
    Class => Type. camelCase => PascalCase ;)
    – mmx
    Oct 13, 2009 at 8:08

3 Answers 3

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

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

1
3

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.

1
  • Lol, sorry DerMike I didn't realise how patronizing this sounded!
    – Dunc
    Mar 23, 2011 at 9:04
1

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

For example, your code would be:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.