Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if a value can be cast to a generic type?

I have a method wrapping some external API call which often returns null. When it does, I want to return a default value. The method looks like this

public static T GetValue<T>(int input)
{
    object value = ExternalGetValue(input);
    return value != null ? (T)value : default(T)
}

The problem is that (T)value might throw an invalid cast exception. So I thought I would change it to

    var value = ExternalGetValue(input) as Nullable<T>;

but this requires where T : struct, and I want to allow reference types as well.

Then I tried adding an overload which would handle both.

public static T GetValue<T>(int input) where T : struct { ... }
public static T GetValue<T>(int input) where T : class { ... }

but I found you can't overload based on constraints.

I realize I can have two methods with different names, one for nullable types and one for nonnullable types, but I'd rather not do that.

Is there a good way to check if I can cast to T without using as? Or can I use as and have a single method which works for all types?

like image 312
Kris Harper Avatar asked Mar 16 '12 16:03

Kris Harper


1 Answers

You can use is:

return value is T ? (T)value : default(T);

(Note that value is T will return false if value is null.)

like image 147
Jon Skeet Avatar answered Sep 28 '22 08:09

Jon Skeet