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

I have a method that wraps an external API call that often returns null . When this happens, I want to return the default value. The method is as follows

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

The problem is that (T)value can cause an invalid cast exception. So I decided to change it to

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

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

Then I tried to add overload, which will 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 that you cannot overload based on restrictions.

I understand that I can have two methods with different names: one for types with a null value and one for non-rotating types, but I would not do that.

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

+4
source share
1 answer

You can use is :

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

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

+7
source

Source: https://habr.com/ru/post/1401859/


All Articles