user3779002
user3779002

Reputation: 620

C# comparing types for equality, with those types as parameters

I need to compare types in C# flexibly, for the purpose of testing types hierarchical relationships. My first try is

public class ParentInfo<PT> {  // PT = parent type expected
    
    public static bool hasParent(LDBRootStructs item) {
        var parent = item.parent;
        var rightParent = parent is PT;  // << this is the type test I want

This is fine but it means instantiating the generic parameter PT to a known class at compile time. I need it as a variable so I tried this instead

public static class ParentInfo2 {  // PT = parent type expected
    
    public static bool hasParent2(LDBRootStructs item,
                                      Type PT) {
        var parent = item.parent;
        var rightParent = parent is PT; <<< error here

but it complained “ Cannot implicitly convert type 'System.Type' to 'LDB.LDBRootStructs' ” and additionally I can't pass in the requested type as a parameter.

I can work around this by adding a test to each of my classes (each class has myOwnType virtual func which returns an int that is fixed for each class, just compare these ints), but is there an easier way? I’ve been looking at GetType and related but it’s unclear.

I need to do this to create an interpreted DSL so it has to be flexible. I’ve looked for previous answers to this (this is SO, they must exist!) but I don’t know what to look for.

-- edit, realised just a way to get a unique id (string, int, whatever) from a class would likely suffice.

Upvotes: 1

Views: 1137

Answers (3)

David Browne - Microsoft
David Browne - Microsoft

Reputation: 88996

The reflection-based equivalent to

bool IsOfType<T>(object o)
{
    return o is T;
}

uses Type.IsAssignableFrom

bool IsOfType(object o, Type t)
{
    return t.IsAssignableFrom(o.GetType());
}

Upvotes: 1

Jamiec
Jamiec

Reputation: 136094

You're trying to compare an instance of a class to an instance of Type - that wont work (or at least won't do what you expect).

Compare the type of parent to the type PT

var rightParent = parent.GetType() == PT; 

This will only match exactly. For a hierarchy/inheritance chain of types you could also use

var rightParent = PT.IsAssignableFrom(parent.GetType()); 

Upvotes: 4

Klamsi
Klamsi

Reputation: 906

This should work

        var foo = new Foo();
        Type bar = typeof(Foo);

        if (foo.GetType().Equals(bar))
        {

        }

Upvotes: -1

Related Questions