5

I wanna know is there any way to pass generic type to another Class as an argument. In other words. I have SomeClass<T> and AnotherClass. I wanna AnotherClass to have an instance field of Type <T> who would be initialized in constructor.

(I want SomeClass to be list of AnotherClass objects. Another Class would have 3 instance fields reference to previous AnotherClass object reference to next AnotherClass object and a T type field.

Davin Tryon
  • 66,517
  • 15
  • 143
  • 132
user2184057
  • 924
  • 10
  • 27
  • If you're looking for runtime type deduction, as in not making your class generic and making a member of the class of a variant type, I don't believe that's possible (out of the box) with C#. You can do it in a makeshift way where the constructor takes in an object, and stores both the object and the Type of the object. – Will Custode Mar 18 '13 at 21:34
  • 1
    http://stackoverflow.com/questions/2107845/generics-in-c-using-type-of-a-variable-as-parameter – MethodMan Mar 18 '13 at 22:02
  • To me, this question does not look like a duplicate of the one referenced above the original question. In _this_ question, the type would be known at compile time. It is about enforcing that related classes use the same actual type for the generic type parameter when used. – R. Schreurs Aug 28 '14 at 10:31

2 Answers2

1

Sounds like you're making a generic container. You need something like:

class Container<T>
{
    public T Value;

    public Container( T rhs )
    {
        Value = rhs;
    }
}

That's basic generics in C#. If you provide more description, I can better answer your question, but based on the info provided, this is what you're looking for.

Jonathan Wood
  • 65,341
  • 71
  • 269
  • 466
Will Custode
  • 4,576
  • 3
  • 26
  • 51
1
class MyClass<T> {
    public List<T> myList;

    public MyClass() {
        this.myList = new List<T>();
    }
}

Like that? I'm not sure I 100% understand the question.

Mike Caron
  • 14,351
  • 4
  • 49
  • 77