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?
You can use is
:
return value is T ? (T)value : default(T);
(Note that value is T
will return false
if value
is null.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With