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.

3
  • That works for no parameters constructor. My case is with a parameter, Commented Apr 9, 2013 at 13:10
  • 1
    Well, you don't read the post attentively enough. The post give you the exact procedure to resolve your problem. Commented Apr 9, 2013 at 13:12
  • Oh thanks, I didn't saw other answers. It worked. Commented Apr 9, 2013 at 13:17

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

6 Comments

I have parameters to my generic object. Will Activator work for this?
Yes. 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.
What if I remove new()?
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<T> as a parameter for the BaseClass constructor, and write it like this: BaseClass<Orange> orangeBase = new BaseClass<Orange>(()=> new Orange("tasty");
(T) Activator.CreateInstance(typeof(T),"SomeText");
|
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.