Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create list of generics

I have base class for my entities

public class Entity<T> where T : Entity<T>, new()
{
    public XElement ToXElement()
    {
    }
    public static T FromXElement(XElement x)
    {
    }
}

I have to use this strange construction Entity<T> where T : Entity<T>, because i want static method FromXElement to be strongly-typed Also, i have some entities, like that

public class Category : Entity<Category>
{
}
public class Collection : Entity<Collection>
{
}

How can i create a generic list of my entities, using base class?

var list = new List<Entity<?>>();
list.Add(new Category());
list.Add(new Collection());
like image 689
Evgraf Avatar asked Oct 10 '12 19:10

Evgraf


People also ask

What is generic List in Java?

The Java Generics programming is introduced in J2SE 5 to deal with type-safe objects. It makes the code stable by detecting the bugs at compile time. Before generics, we can store any type of objects in the collection, i.e., non-generic. Now generics force the java programmer to store a specific type of objects.

What is generic List in C#?

The Generic List<T> Class in C# is a collection class that is present in System. Collections. Generic namespace. This Generic List<T> Collection Class represents a strongly typed list of objects which can be accessed by using the index.


2 Answers

You can't with that definition. There is no "common base class" between Category and Collection (other than object, of course).

If there were, say if Entity<T> were defined as:

public class Entity
{
}

public class Entity<T> : Entity where T : Entity<T>, new()
{
    public XElement ToXElement()
    {
    }
    public static T FromXElement(XElement x)
    {
    }
}

then you could do

var list = new List<Entity>();
list.Add(new Category());
list.Add(new Collection());

But what would that buy you?

like image 76
D Stanley Avatar answered Sep 25 '22 08:09

D Stanley


Create a marker interface:

public interface IAmAGenericEntity { }

public class Entity<T> where T : IAmAGenericEntity, new()
// ...

public class Category : Entity<T>, IAmAGenericEntity
// ....

var list = new List<IAmAGenericEntity>();
// ...
like image 27
Dennis Traub Avatar answered Sep 22 '22 08:09

Dennis Traub