Click here to Skip to main content
15,887,380 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi -

I'm learning more about generics and I'm wondering how to instantiate a generic typed class. Here is the class

public class MyGenericCommand<T> : ICommand<T,T> where T : IMyBaseStuff<IBaseStuff>
{
 ///reset of class code here
}


In another class would want some thing like
private MyGenericCommand<some class> _command;


Thanks

What I have tried:

c# Generic on variable declaration, is this possible? - Stack Overflow[^]
Posted
Updated 6-May-17 1:16am

 
Share this answer
 
Doesn't make a lot of sense, but

public interface ICommand<T1, T2>
{
    T1 PropA { get; set; }
    T2 PropB { get; set; }
}

public interface IBaseStuff
{
    int PropD { get; set; }
}

public interface IMyBaseStuff<T>
{
    T PropC { get; set; }
}

public class MyGenericCommand<T> : ICommand<T, T> where T : IMyBaseStuff<IBaseStuff>
{
    public T PropA { get; set; }
    public T PropB { get; set; }
}

public class BaseStuff : IBaseStuff
{
    public int PropD {get;set;}
}

public class MyCommandClass : IMyBaseStuff<IBaseStuff>
{
    public IBaseStuff PropC {get; set;}
}


Usage

MyGenericCommand<MyCommandClass> _command = new MyGenericCommand<MyCommandClass>();
_command.PropA = new MyCommandClass();
_command.PropB = new MyCommandClass();

_command.PropA.PropC = new BaseStuff();
_command.PropA.PropC.PropD = 123;
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900