Nodoid
Nodoid

Reputation: 1561

Passing generic into a class constructor list

I have a class that takes a generic as a parameter like this

public MyNewClass(string text, T myClass, int f, bool test = false)

The compiler is complaining about T myClass.

I know I can pass "defined" generic classes to a class constructor (such as List, Dictionary etc) and have seen that this can be done in C# as well, but can't find a reference to it.

Upvotes: 2

Views: 3597

Answers (2)

Aron
Aron

Reputation: 15772

I suspect that the issue you are facing is that the following does not compile

public class Foo<T>
{
    public Foo(string s, T t) { }
}

var foo = new Foo("Hello", new Something());

The fix to this is to specify in the constructor.

var foo = new Foo<Something>("Hello", new Something());

However, this still seems a little strange given that normally, the C# compiler can infer the type of T.

The problem here is that the C# compiler is only allowed to infer generics on the first parameter of a method. So the following IS allowed.

public class Foo<T>
{
    public Foo(T t, string s) { }
}

var foo = new Foo(new Something(), "Hello");

Upvotes: 0

Christos
Christos

Reputation: 53958

You should declare the generic parameter, when you declare your class.

public class MyNewClass<T>
{


}

Then this parameter could be accessible from any of the class's methods. When you will create an instance of your MyNewClass, you should define also the type of T, for instance:

var instanceOfMyNewClass = new MyNewClass<className>(text, classIntance, f, true);

where classInstance is an instance of an object of type className.

A good introduction about generics is here.

Upvotes: 4

Related Questions