I want to create generic function which will take value of some type as parameter.
MyGenericClass<T>(parameter) (parameter could be also set by property there is no need to use constructor here)MyGenericClass<NotNullType(T)>(parameter.Value) example: for parameter int? x, function should return MyGenericClass<int>(x.Value).Here is code which I've written to do such operation but without success:
private MyGenericClass GetMyGenericClassOrNull<T> (T value) {
if (value != null) {
var underlyingType = Nullable.GetUnderlyingType(typeof(T));
if (underlyingType == null) {
return new MyGenericClass<T>(value);
} else {
return new MyGenericClass<underlyingType>(value);
}
}
return null;
}
As you can expect line: return new MyGenericClass<underlyingType>(value); is problematic here.
Is there any way to do such thing?
You could try with:
public class MyGenericClass
{
}
public class MyGenericClass<T> : MyGenericClass
{
public MyGenericClass(T value)
{
}
}
public static MyGenericClass GetMyGenericClassOrNull<T>(T? value) where T : struct
{
if (value != null)
{
return new MyGenericClass<T>(value.Value);
}
return null;
}
public static MyGenericClass GetMyGenericClassOrNull<T>(T value)
{
if (value != null)
{
return new MyGenericClass<T>(value);
}
return null;
}
You have two separate methods. Nullable types will go to the first one, where T is the non-nullable "base" type.
Note that you can make the signatures public static MyGenericClass<T> without any problem if you want. It isn't clear how your MyGenericClass is built.
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