Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create instance of generic class based on nullable type

Tags:

c#

I want to create generic function which will take value of some type as parameter.

  • This type could be nullable or not.
  • If value is null function should returns null.
  • If it's not null, and it's not nullable type than function should returns MyGenericClass<T>(parameter) (parameter could be also set by property there is no need to use constructor here)
  • If it's not null, and it's nullable type than function should return something like 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?

like image 869
Mateusz Rogulski Avatar asked Mar 24 '26 22:03

Mateusz Rogulski


1 Answers

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.

like image 147
xanatos Avatar answered Mar 27 '26 19:03

xanatos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!