Raheel Khan
Raheel Khan

Reputation: 14787

Generic<T>() vs Generic(System.Type). Generics vs Reflection

Where is it more appropriate to use

class Entity<T> {}

new Entity<User>()

as opposed to

class Entity
{
   public Entity(System.Type type) 
   {
   }
}

new Entity(typeof(User))

I realized the significance of System.Type after dealing with reflection and code generation. After a month of development and getting familiar, I look back at my choices with skepticism.

This would probably not apply to you if you do not need reflection.

Upvotes: 2

Views: 348

Answers (3)

Marc Gravell
Marc Gravell

Reputation: 1062955

The generic approach Entity<T> has the ability to use generic type constraints to enforce both rules and features at compile-time (i.e. T must have a public parameterless constructor and be a reference-type, for example). It doesn't need any storage space for the type on each instance, since Entity<X> and Entity<Y> are discreet types - but as a re-statement of that: you cannot have a heterogeneous List<Entity<?>> (unless you have a common base-type) for the same reason.

It is much harder to use generics if the type is known only at run-time.

Upvotes: 2

Maheep
Maheep

Reputation: 5605

If you use second approach you will have type cast the user object(which you will have, most probably) every time in entity class. Where as if you use generic i.e. first approach you will not require this.

Upvotes: 0

BrandonAGr
BrandonAGr

Reputation: 6017

It depends on what you have inside of Entity. Do you have any fields of type T or parameters to methods of type T in the Entity class? If you are only ever doing typeof(T) inside Entity then it probably would be simpler to pass in a System.Type like in your second example.

Another difference would be that you can use constraints with generics, so you could do class Entity<T> where T: ISomeInterface

Upvotes: 1

Related Questions