I have a generic method and need to guarantee that my method returns nullable<T>
(ex. source is List<int>
or List<int?>
must returns int?
) and I want to return null instead of default (ex. default of int is 0. in this case I want to return null). It can be possible to add constraints on type parameter(https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/constraints-on-type-parameters) but whit this approach I must have 2 methods (one of them with struct constraint and another with class constraints)
my method is:
public static T? ElementOrNull<T>(List<T> source, int? index)
{
if (source == null || index == null || source.Count <= index)
return null;
return source[index.Value];
}
I try Convert.ChangeType()
and reflection(Activator.CreateInstance()
and Activator.CreateInstance<T?>()
) but I can't solve this problem.
Any and all feedback is appreciated. Thank you
Note: I checked all the questions about generics and casting of them in StackOverflow but they didn't help me