Tom
Tom

Reputation: 3183

Generics in C# with "as" and "is" having troubles, "is" check fails

I'm running into troubles with C# generics:

MappingAdapter is a common abstract base class that FullMappingAdapter and LiteMappingAdapter inherit from / implement.

Creating an instance of my generic class session:

session = new Session<FullMappingAdapter>(
// ...
)

In session, deciding what kind of session we are:

// class declaration:
public class Session<T> :  ISession
                           where T : MappingAdapter {
    // ...
    // method body:
    T t = null;
    if (t is FullMappingAdapter) {
        // need parameter, cannot use where T : new() above
        t = new FullMappingAdapter(someData) as T;
    } else if (t is LiteMappingAdapter) {
        t = new LiteMappingAdapter(someData) as T;
    } else {
        throw new NotSupportedException("Unknown Adapter specified, please fix.");
    }

    // ... more methods here ...        

}

I always get NotSupportedException thrown. Also, when looking at my stack in the debugger it says "FullMappingAdapter" in the "type" column of t, which is correct, and what I expected. But why doesn't the "is" keyword also recognize the type?

What am I doing wrong?

Upvotes: 0

Views: 105

Answers (3)

Vinod Kumar Y S
Vinod Kumar Y S

Reputation: 628

You have to check like this

if (typeof(T) == typeof(FullMappingAdapter))

Upvotes: 1

Alexei Levenkov
Alexei Levenkov

Reputation: 100527

null is never anything.

You want to check typeof(T) for being exact type (or maybe IsAssignableFrom) instead.

Exact match (not the same as is FullMappingAdapter because it will not include derived types)

if(typeof(T) == typeof(FullMappingAdapter))

Assignable - same as is FullMappingAdapter:

if (typeof(FullMappingAdapter).IsAssignableFrom(typeof(T))

Upvotes: 10

Adi Lester
Adi Lester

Reputation: 25201

You should modify your check to use typeof:

if (typeof(T) == typeof(FullMappingAdapter))

and so on

Upvotes: 3

Related Questions