0

I am making a base class from which other classes can be derived.

public class BaseClass<T> where T
{
    public BaseClass()
    {
        TClassObject = new T("SomeText"); // Error here
    }

    public T TClassObject { get; set; }
}

'T': cannot provide arguments when creating an instance of a variable type.

What I am missing here.

fhnaseer
  • 7,159
  • 16
  • 60
  • 112

2 Answers2

5

From MSDN:

The new constraint specifies that any type argument in a generic class declaration must have a public parameterless constructor.

So it needs to be parameterless. You may want to look at Activator.CreateInstance

http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx

Conrad Clark
  • 4,533
  • 5
  • 45
  • 70
  • I have parameters to my generic object. Will Activator work for this? – fhnaseer Apr 09 '13 at 13:02
  • 1
    Yes. http://msdn.microsoft.com/en-us/library/wcxyzt4d.aspx. `Creates an instance of the specified type using the constructor that best matches the specified parameters.` Check it out. – Conrad Clark Apr 09 '13 at 13:02
  • What if I remove new()? – fhnaseer Apr 09 '13 at 13:07
  • No problem, since you won't be calling new() anyway. Just be careful not to hurt your code readability and maintenance by using `Activator.CreateInstance`. You could also accept a Func as a parameter for the BaseClass constructor, and write it like this: `BaseClass orangeBase = new BaseClass(()=> new Orange("tasty");` – Conrad Clark Apr 09 '13 at 13:08
  • var obj = Activator.CreateInstance(typeof(T), "SomeText"); Now this returns me object. How I cast this to T type? – fhnaseer Apr 09 '13 at 13:14
  • 1
    `(T) Activator.CreateInstance(typeof(T),"SomeText");` – Conrad Clark Apr 09 '13 at 13:25
2

The where T : new() constraint states that T must have a parameterless constructor. Your code is calling into a constructor that takes a string parameter, and it isn't guaranteed that your T will have such a constructor.

It is not possible in C# to create a constraint on a specific constructor signature. If you need this functionality, you're better off using something like one of the answers in this thread.

Community
  • 1
  • 1
goric
  • 11,491
  • 7
  • 53
  • 69