Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set class generic value in constructor only

Tags:

c#

.net

generics

There is any way to set the generic type (T) of class in the constructor only, but not in the declaration?

public class Gen<T>
{
}

public class Da
{
}

public class Program
{
    public static Gen<?> gen;

    public static void Main(string[] args)
    {
        gen = new Gen<Da>();
    }
}
like image 622
Matan Shahar Avatar asked Mar 04 '26 18:03

Matan Shahar


1 Answers

If I understand your requirements correctly, the easiest way to achieve this is to have a non-generic interface:

interface IGen { }

Then your generic class can be:

class Gen<T> : IGen { }

And the usage is:

IGen objectGen = new Gen<object>();
IGen intGent = new Gen<int>();
like image 105
Rich O'Kelly Avatar answered Mar 06 '26 07:03

Rich O'Kelly



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!