C# Generic Class<T> - c#

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>());

Related

C# covariance: classes with different interface signature

I have a base class with the following signature:
abstract class BaseClass<I, S>
Then I define a class with the following signature to extend the BaseClass:
class ExtendedClass<I> : BaseClass<I, int>
So, ExtendedClass sets the S generic type of the BaseClass with int argument. I am using the classes as it follows:
BaseClass<I, S> anInstance = new ExtendedClass<I>();
This throws the following error:
Cannot implicitly convert type ExtendedClass to BaseClass
Some simplified context:
abstract class Analyzer<I, S>
{
protected BaseClass<I, S> Run()
{
// implements some logic here, based their results different
// extensions of BaseClass can be returned. This logic is
// simplified as the following.
switch(some_logic_output)
{
case true: return new ExtendedClass<I>(){ /*some property settings*/ };
case false: return null;
}
}
}
You should specify for the reference what S and I are. If you are outside the scope of the class:
BaseClass<SomeClass, int> anInstance = new ExtendedClass<SomeClass>();
If you are in the scope of the class
BaseClass<I, int> anInstance = new ExtendedClass<I>();
S is a name given for the generic type in the context of the BaseClass. It does not exist outside of it and when defining a reference as you did you must give the concrete type.
The second type parameter must be set to int:
BaseClass<I, int> anInstance = new ExtendedClass<I>();
Obviously, I also must be a concrete type or another type parameter in a generic class.

regarding the use of new Constraint in c#

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.

Generic method compile time error

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.

Create generic class with internal constructor

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);
}
}

C# Generics - Constraints on type parameters

I'm trying to build a factory method that uses the generics feature of C#.
In this factory method I would like to constraint it to some specific classes, all of which do not have a default constructor.
Here is my example. Can someone tell me if it's possible to run it?
public class AbstractClass {
//this abstract class does not have a default constructor, nor its subclasses
public AbstractClass(SomeClassName obj) {
//use obj for initialization
}
}
//this factory class should create objects of type T that inherit
//from AbstractClass and invoke the non-default constructor
public class FactoryClass {
public static T BuildObject<T> (SomeClassName obj) where T: AbstractClass {
return new T(obj); //does not work?!?!?!
}
}
//Edit: ANSWER!!!
public static T BuildObject<T>(SomeClassUsedForTheConstructor item) where T : SomeAbstractClass {
return (T) Activator.CreateInstance(typeof (T), item);
}
I like to use Activator.CreateInstance(typeof(T)) in my generics that need to create new objects of type T. It works really well.
Look at the Type class and GetConstructor. Once you get the ConstructorInfo object, use the Invoke Method.
var x = typeof(T);
var t = x.GetConstructor(new[] {obj.GetType()});
object u = t.Invoke(<inputs>);
I don't think you can instantiate generic types without a default constructor on the constraint type.
Consider instead specifying an interface IAbstractClass, such that your factory class can set the SomeClassName parameter as a property of IAbstractClass.
Additionally, if a SomeClassName instance is required for initializing AbstractClass, consider also having an empty default constructor, but a rich initializer method defined in IAbstractClass. For example:
public interface IAbstractClass { void Initialize(SomeClassName obj); }
That way, your static BuildObject method instead does:
public static T BuildObject<T>(SomeClassName obj) where T: AbstractClass
{
T newObject = new T();
IAbstractClass ac = newObject as IAbstractClass;
ac.Initialize(obj);
}
No, what you are trying to do is not possible using the built-in generic constraints alone. The new keyword only allows you to constrain the generic type to having a default constructor.

Categories