I know the theory, they are awesome, the ones included in the framework simplify many things, they even have performance gain.
There are many answers about this topic with very nice examples but typically with low practical value to me or examples that are already present in the framework.
The question is, in which cases you decide to write a class of your own that uses generics?

- 2,245
- 3
- 25
- 45
-
seems u skipped the chapter about patterns, try factory as the most simple example. – Jaster Jan 21 '11 at 15:14
4 Answers
I'm using generics every time I need to apply same algorithm / same logic on different types of objects.
Example is generic repository:
public interface IRepository<T> where T : class, IEntity
{
IQueryable<T> GetQuery();
void Update(T entity);
void Insert(T entity);
void Delete(int id);
}
public interface IEntity
{
int Id { get; set; }
}

- 360,892
- 59
- 660
- 670
I use generics whenever a class performs a set of operations on a yet-to-be-defined type.
For instance, imagine that you implement a set of mathematical operations, but would like the user of your class to be able to decide the actual number type (int
, short
, ...). By not specifying a type (by making it generic), the generic class can be more widely used.
Another, related, benefit is that the code generated for the generic class will actually be more specific, using eg. less cast operations and potentially less run-time tests. The generic containers in the .NET framework are a good example.

- 7,339
- 2
- 34
- 55
-
Thats a good argument, not a real practical example but still valid – Cristian T Jan 21 '11 at 10:22
-
Very practical! I implemented point and vector classes using generics, and code processing geometrical operations on those. Execution time is highly dependent on the storage type (8 bit, 16 bit, floating point), and which type to use depends on the application. By using generics, I can always be sure to use the best possible code for the specific application. – Daniel Gehriger Jan 21 '11 at 10:29
-
2@Daniel: Yes it is practical, the only thing I'm missing in .NET is base type for numbers so that I can restrict type like vector
where T : number. – Ladislav Mrnka Jan 21 '11 at 10:36 -
1@Ladislav: yes, that's a major drawback when compared to C++ templates. See [this answer](http://stackoverflow.com/questions/63694/creating-a-math-library-using-generics-in-c) for a work-around to get at least some of this functionality. – Daniel Gehriger Jan 21 '11 at 10:41
-
1@Daniel Gehriger: While not supported natively by the framework, there is a easy workaround for this. Look at this blog: http://rogeralsing.com/2008/02/27/linq-expressions-calculating-with-generics/. – Steven Jan 21 '11 at 11:03
Wow - too many examples (that are potentially too involved for a quick SO answer...) that I can give.
I use generics in many many places (especially to wrap up common patterns that apply in many scenarios). However, one of the most benefitial uses to which I've put them is to speed up reflection-based or other dynamic code which will change depending on the type of an operand, whilst simultaneously hiding it away.
So, for example (a fictional one because my real-world examples will be too involved and abstract without a lot of background) , let's say I have a component which uses strings to retrieve data values from objects almost exclusively. Of course, if it did it once or twice then not a problem, keep the reflection, but if it does it a lot then what you want to do is to compile dynamic delegates that can retrieve the values much faster. So,
public static class NamedValueAccessor<T>
{
private Dictionary<string, Func<T, object>> _accessors;
private Dictionary<string, Action<T, object>> _writers;
public object GetValue(T instance, string name) { }
public void SetValue(T instance, string name, object newValue) { }
}
GetValue
and SetValue
can reflect over the type T
for its properties, checking the CanRead
and CanWrite
values of PropertyInfo
. Once everything's confirmed as being okay, they can dynamically build a Read/Write delegate using System.Linq.Expressions (easy, since all the reflection info is available) and cache it in the dictionary.
Oh yeah - forgot in my first draft - note that the SetValue
delegates can only be compiled with expressions in .Net 4.0 unless you are writing the IL manually.
With this as the base you can then use this class in other generics, perhaps extension methods:
public static GetPropertyValue<T>(this T instance, string name)
{
return NamedValueAccessor<T>.GetValue(instance, name);
}
Which, because it has no constraints can apply to all types.
And also by reflection if all you have is, say, an object
- you can use it's GetType()
method to get the runtime type, do a typeof(NamedValueAccessor).MakeGenericType(o.GetType()).GetMethod(...).Invoke(...)
. Following the same pattern, however, in this case you're better of building a dynamic cache of delegates for each Type
that are baked over the correct NamedValueAccessor<T>.GetValue
method for the incoming type.
UPDATE
So, to explain what the generic has done for us in this example:
1) Type-based property caches will be resolved by the compiler if the generic type parameter is known at compile time (i.e. NamedValueAccessor<MyType>.GetValue("Foo")
) compiles to a particular instance of the generic. All that remains to be done at run time is lookup the delegate in the dictionary and execute it.
2) The caches for separate types are kept apart
3) The caches can be primed in the static class' static constructor with a simple reflection over the type to get all the properties that would be supported and pre-compiling all the delegates. Of course you have to be careful with this code to make sure it can't throw a runtime error - nobody likes TypeInitializationException
s. If you do this, then you don't have to worry about multithreaded environments either - the cache is immutable.
On point 3 - if the type is an IDynamicObject, then of course this strategy fails - but you can delegate to the instance's dynamic interface.
END UPDATE
In practise, my use of this is to do more complicated things than just wrapping property setters and getters (the code in the ComponentModel namespace is probably better for this - as in the way that Mvc leverages it), but properly woven these kinds of solutions provide excellent performance and accessibility to the end-user (the application coder in my case).
I also expect that this answer will be too abstract to get any votes, but I'm throwing it out there anyway because we don't provide answers to get votes - but to inform the person asking the question :)

- 41,961
- 13
- 104
- 160
-
It is also this kind of thing that is at the heart of the DLR, although the caches and logic behind are far more in depth than I suggest here – Andras Zoltan Jan 21 '11 at 10:40
-
So I understand that you use this technique to boost performance by having the compiler explode the code inside the generics class, instead of using reflection right? – Cristian T Jan 21 '11 at 10:49
-
@Cristian - was going to answer in a comment; but thought it best to add extra information to the answer giving some justifications. – Andras Zoltan Jan 21 '11 at 10:59
I've used generics to add an extension method to objects that implement a couple of interfaces, so
public static MyExtension<T>(this T myobject) where T : ISomeInterface, ISomeOtherInterface
{
//Do some stuff on myObject
}

- 4,327
- 23
- 25