Orestis P.
Orestis P.

Reputation: 825

c# find method overload from generic type at runtime

Consider the following methods:

public void foo(int a) {
   //do something with a
}

public void foo(ushort a) {
   //do something with a
}

public void foo<T>(Nullable<T> a) where T : struct {
     if (!a.HasValue) {
        return;
     }

     foo(a.Value); //find appropriate method based on type of a?
}

Is there any way to find the respective method to call based on the generic type of the parameter? For example, if (T)a is an int, call the first method, if it's a ushort, call the second one. If no such method exceeds, perhaps throw a runtime exception.

I've tried the following:

public void foo<T>(Nullable<T> a) where T : struct {
     if (!a.HasValue) {
        return;
     }
     switch(a.Value.GetType()) {
           case typeof(int): foo((int)a.Value); break;
           case typeof(ushort): foo((ushort)a.Value); break;
           //and so on
     }
}

But compiler doesn't like the cast ("Cannot convert type T to int"); Is there any way to achieve what I'm trying to do?

Upvotes: 2

Views: 411

Answers (1)

dcastro
dcastro

Reputation: 68660

try

public void foo<T>(Nullable<T> a) where T : struct {
 if (!a.HasValue) {
    return;
 }

 foo((dynamic)a.Value);
}

a.Value's type will be resolved at runtime by using dynamic, and the appropriate overload will be called.

Upvotes: 3

Related Questions