The following code:
private IList<T> DoStuff<T>()
{
IList<T> res = new List<T>();
for (int i = 0; i < 10; i++)
{
T item = DoOtherStuff<T>();
res.Add(item);
}
return res;
}
private T DoOtherStuff<T>() where T : new()
{
return new T();
}
Generates the following error:
'T' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'DoOtherStuff()'
Please may somebody explain why?
Change
private IList<T> DoStuff<T>()
to
private IList<T> DoStuff<T>() where T : new()
since otherwise you can't guarantee that T has a new() constructor.
Your DoOtherStuff<T> method has the where T : new() constraint. (That is, "T must be a non-abstract type with a public parameterless constructor".)
Your DoStuff<T> method doesn't have that constraint, which means that the compiler can't guarantee that all type arguments T that can legally be used for DoStuff will meet the where T : new() constraint required by DoOtherStuff.
DoOtherStuff's T specifies that T : new(), which means it has a public parameterless constructor. DoStuff's T has no restrictions, so you might not be able to say new T(). You should add where T : new() do DoStuff.
Related
Why this gives a compiler error?
public class EventAggregationHelper {
public static SubscriptionToken SubscribeToEvent<T>( IEventAggregator eventAggregator ) where T : EventBase {
T evt = eventAggregator.GetEvent<T>();
//T evt = eventAggregator.GetEvent<T>();
return null;
}
}
The error is:
Severity Code Description Project File Line Suppression State
Error CS0310 'T' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'TEventType' in the generic type or method 'IEventAggregator.GetEvent()' EntitySetGridTWPF D:\DEVELOPER.NET\Comercial\EntityBookCommon\EntitySetGridTWPF\EventAggregation\EventAggregationHelper.cs 9 Active
on the line:
T evt = eventAggregator.GetEvent<T>();
I've used this approach for calling other generic methods before and has worked. What has GetEvent so special?
Thanks in advance.
IEventAggregator.GetEvent has a new() constraint, which means that your subscription also needs to add the new() constraint and that also needs to be fulfilled by your implementation class T, which must have a public parameterless (default) constructor (and must not be abstract.)
public static SubscriptionToken SubscribeToEvent<T>
(IEventAggregator eventAggregator) where T : EventBase, new() {
I have an interface
public interface IFormBuilder<T,K> where T : Entity where K : Form
{
K Build(T entity);
}
I want to be able to pass in an entity and have it return a Form object from the Build method (Form object is not a Windows Form object it is my own class)
It seems to register fine using the code
container.RegisterType(typeof(IDummyFormBuilder<,>), typeof(DummyFormBuilder<,>));
I inject the IFormBuilder into the constructor of a FormProcessingService
private readonly IFormBuilder<applicationEntity, Form> _formBuilder;
public FormProcessingService(IFormBuilder<applicationEntity, Form> formBuilder)
{
_formBuilder = formBuilder;
}
The problem is in declaring the FormBuilder class
public class FormBuilder<T, K> : IFormBuilder<T, K>
{
public K Build(T entity)
{
return new Form();
}
}
The error message I get is
Error CS0314 The type 'T' cannot be used as type parameter 'T' in the
generic type or method 'IFormBuilder'. There is no boxing
conversion or type parameter conversion from 'T' to 'Entity'.
The type 'K' cannot be used as type parameter 'K' in the generic type
or method 'IFormBuilder'. There is no boxing conversion or type
parameter conversion from 'K' to 'SmartForm'.
Can anybody explain what is happening here?
In your interface definition you have these generic type constraints:
where T : Entity where K : Form
When you implement the interface, these type constraints are not inherited automatically, so you need to declare them on your class as well:
public class FormBuilder<T, K> : IFormBuilder<T, K>
where T : Entity where K : Form
{
// your class code
}
This tells compiler, that the generic type constraints on class FormBuilder are compatible with the ones from IFormBuilder and they can be used together.
Even if matching constraints are use there is still one issue in your method declaration:
public K Build(T entity)
{
return new Form();
}
Compiler complains here that there is no implicit conversion from Form to K. In order to fix that, there are 2 approaches you can take.
First approach is to convert Form to K, like this:
public K Build(T entity)
{
return (K)(new Form());
}
Second approach can be used if your class FormBuilder has a constructor with no parameters. In this case you can add constraint new() to your class declaration and then you can create new form using new K():
public class FormBuilder<T, K> : IFormBuilder<T, K>
where T : Entity where K : Form, new()
{
public K Build(T entity)
{
return new K();
}
}
How can I add a generic Type to my list?
I tried to create an object of T but this doesn't work neither.
class Bar<T> where T : IDrink
{
List<T> storage = new List<T>();
public void CreateDrink()
{
storage.Add(T); //<- This doesn't work
}
}
T is a type not an instance of that type. So you need a parameter in CreateDrink or use a factory method that returns a new instance of T.
If you want to create an instance the generic constraint must include new()
class Bar<T> where T : IDrink, new()
{
List<T> storage = new List<T>();
public void CreateDrink()
{
storage.Add(new T());
}
}
The new constraint specifies that any type argument in a generic class
declaration must have a public parameterless constructor. To use the
new constraint, the type cannot be abstract.
You can do it like:
storage.Add(Activator.CreateInstance<T>());
i never use new Constraint because the use is not clear to me. here i found one sample but i just do not understand the use. here is the code
class ItemFactory<T> where T : new()
{
public T GetNewItem()
{
return new T();
}
}
public class ItemFactory2<T> where T : IComparable, new()
{
}
so anyone please make me understand the use of new Constraint with small & easy sample for real world use. thanks
This constraint requires that the generic type that is used is non-abstract and that it has a default (parameterless) constructor allowing you to call it.
Working example:
class ItemFactory<T> where T : new()
{
public T GetNewItem()
{
return new T();
}
}
which obviously now will force you to have a parameterless constructor for the type that is passed as generic argument:
var factory1 = new ItemFactory<Guid>(); // OK
var factory2 = new ItemFactory<FileInfo>(); // doesn't compile because FileInfo doesn't have a default constructor
var factory3 = new ItemFactory<Stream>(); // doesn't compile because Stream is an abstract class
Non-working example:
class ItemFactory<T>
{
public T GetNewItem()
{
return new T(); // error here => you cannot call the constructor because you don't know if T possess such constructor
}
}
In addition to Darin's answer, something like this would fail because Bar does not have a parameterless constructor
class ItemFactory<T> where T : new()
{
public T GetNewItem()
{
return new T();
}
}
class Foo : ItemFactory<Bar>
{
}
class Bar
{
public Bar(int a)
{
}
}
Actual error is: 'Bar' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'ItemFactory<T>'
The following would also fail:
class ItemFactory<T>
{
public T GetNewItem()
{
return new T();
}
}
Actual error is: Cannot create an instance of the variable type 'T' because it does not have the new() constraint
The new constraint specifies that any type argument in a generic class declaration must have a public parameterless constructor.
quoted from the official website
You can read new() as if it is an interface with a constructor. Just like that IComparable specifies that the type T has a method CompareTo, the new constraint specifies that the type T has a public constructor.
In your example, the constraint acts on <T> in the class declaration. In the first case, it requires that the generic T object has a default (parameterless) constructor. In the second example, it requires that T should have a default, parameterless constructor and that it must implement the IComparable interface.
Is it possible to construct an object with its internal constructor within a generic method?
public abstract class FooBase { }
public class Foo : FooBase {
internal Foo() { }
}
public static class FooFactory {
public static TFooResult CreateFoo<TFooResult>()
where TFooResult : FooBase, new() {
return new TFooResult();
}
}
FooFactory resides in the same assembly as Foo. Classes call the factory method like this:
var foo = FooFactory.CreateFoo<Foo>();
They get the compile-time error:
'Foo' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'TFooType' in the generic type or method 'FooFactory.CreateFoo()'
Is there any way to get around this?
I also tried:
Activator.CreateInstance<TFooResult>();
This raises the same error at runtime.
You could remove the new() constraint and return:
//uses overload with non-public set to true
(TFooResult) Activator.CreateInstance(typeof(TFooResult), true);
although the client could do that too. This, however, is prone to runtime errors.
This is a hard problem to solve in a safe manner since the language does not permit an abstract constructor declaraton.
The type argument must have a
public parameterless constructor. When used together with other
constraints, the new() constraint must
be specified last.
http://msdn.microsoft.com/en-us/library/d5x73970.aspx
edit: so no, if you use new() constraint, you cannot pass that class, if you don't use new() constraint you can try using reflection to create new instance
public static TFooResult CreateFoo<TFooResult>()
where TFooResult : FooBase//, new()
{
return (TFooResult)typeof(TFooResult).GetConstructor(System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance, null, new Type[] {}, null).Invoke(new object[]{});
//return new TFooResult();
}
There can be few work-arounds as below but I don't think you want to go that way!
Put switch statement inside Factory
that will create the instance based
on type of type parameter.
Each concrete implementation of FooBase will register with FooFactory passing the factory method to create it self. So FooFactory will use the internal dictionary
Extending on the similar line except mapping between type parameter and concrete implementation would be external code (xml file, configuration etc). IOC/DI containers can also help here.
public class GenericFactory
{
public static T Create<T>(object[] args)
{
var types = new Type[args.Length];
for (var i = 0; i < args.Length; i++)
types[i] = args[i].GetType();
return (T)typeof(T).GetConstructor(types).Invoke(args);
}
}