7

I haven't used Generics in C# for a long while. Every time I think I need to use them I either go in the wrong direction and give up or find that I don't really need them. I feel that I'm missing out or ignoring a technique which could be useful and powerful.

I'm aware of how generics are meant to be used (or at least I think I am). If you have three methods that are all doing the same thing with different types, then using generics enables you to have just one method that will work with these three types.

EDIT (in response to comment)

Are there any code smells or patterns that I should be looking out for?

Note I use List<> a lot, so I'm not ignoring generics in the the standard library. It's just that I've not written custom code using Generics for a while.

gnat
  • 21,442
  • 29
  • 112
  • 288
Daniel Hollinrake
  • 740
  • 1
  • 5
  • 13
  • Whenever you need apply some generic operation to something (which is not as often as you'd think!). It sounds snippy, but it's true. – Joachim Sauer Mar 20 '13 at 11:50
  • I think that's the problem. Right now I'm not finding generic operations. Everything tends to be specific. – Daniel Hollinrake Mar 20 '13 at 11:53
  • 5
    I've been writing both application and framework code a lot in the last years (mostly in Java, but that won't make much of a difference). In application code I *rarely write* classes or methods that apply generics. I might *use* methods and classes that use generics (`List` and other collections most prominently). In framework code (which is, by definition, generic) generics occur much more frequently. – Joachim Sauer Mar 20 '13 at 11:55
  • just think of generic collections ! It may be a good example – Kemoda Mar 20 '13 at 11:56
  • 1
    Can you clarify which of your question is the main question? (1) "What problems can be solved using Generics?" (2) "Are there any code smells or patterns that I should be looking out for?" (On Stackexchange, asking two questions at once makes it more difficult to choose the correct answers.) – rwong Mar 20 '13 at 12:01
  • 1
    "Are there any code smells or patterns that I should be looking out for?" - if you find yourself doing a lot of (down)casting between types, it's usually a hint that generics might be applicable. Also, if you have methods / properties which return `object`. – Daniel B Mar 20 '13 at 12:07
  • 2
    How could you ignore generics if the standard library is full of them? – SK-logic Mar 20 '13 at 13:40
  • 1
    I use List<> a lot, so I'm not ignoring that! It's just that I've not written custom code using Generics for a while. – Daniel Hollinrake Mar 20 '13 at 13:42
  • @JoachimSauer I just got finished typing the exact same answer. Great minds and all ;) – Michael Brown Mar 20 '13 at 14:38

5 Answers5

10

In a nutshell, generics solves the problem of having to use loosely typed objects.

For example, consider ArrayList vs List<T>. It allows you to have a strongly typed collection. list[0] will return type T vs arrayList[0] which will return type object.

But, you can do more with generics than just collections. Consider a generic repository used in an object relational solution:

public class Repository<T> where T : class, IBusinessOBject
{
  T Get(int id)
  void Save(T obj);
  void Delete(T obj);
}

Generics can allow your class to encapsulate various types without requiring source level changes.

Sam
  • 6,152
  • 2
  • 20
  • 34
8

Essentially, generics are a technique for aiding separation of concerns, or the single responsibility principle (SRP), as well as the DRY (Don't Repeat Yourself) principle. Without generics, you will sometimes see type or method names that reference both another type and a task, for example PersonCsvWriter, CustomerRecordSearch or ProductCollection. Unless these types derive from or consume other types that separate these responsibilities, then they are doing two things: e.g. PersonCsvWriter converts Person objects into sets of fields, and writes those fields to a CSV file. This makes your code harder to reuse. If you see this type of thing, it may be a code smell telling you that generics could be put to use.

I'd look out for this particularly if you are defining interfaces or abstract classes. Interfaces define roles in your application and don't make a lot of sense unless there can be multiple providers of that role. If the role is to work with other types, and the interface is not generic, it is very hard to re-implement it. For example, an IMapper<TFrom, TTo> is obviously a lot more reusable than a ICustomerToCustomerViewModelMapper.

You can of course be loosely-generic by treating everything as objects, using reflection and/or casting at runtime (as C#1 coders will remember). This isn't type-safe, having the obvious drawback of making your code harder to debug by allowing it to fail at runtime.

Tim
  • 1,427
  • 10
  • 11
4

This is funny because I find myself writing generic classes and operations all the time. Perhaps because I'm working more on framework level code than client side. Some examples include Generic Repositories, Event Aggregators, and CQRS Command Handlers among others.

Generics are mostly useful in framework level code to enable reuse. If you're just consuming the frameworks, you might not find yourself creating generic functions as much.

Michael Brown
  • 21,684
  • 3
  • 46
  • 83
2

Unless you're programming in Ada, where it comes up all the time, the opportunity to create new generic code is fairly rare. For me, it comes up maybe once every three to five years, long enough that I have to look up the syntax.

The way to tell you need it is when you find yourself copying and pasting code, changing only the types, and you try to fix it using inheritance and it doesn't help.

Karl Bielefeldt
  • 146,727
  • 38
  • 279
  • 479
  • 3
    I would think it had more to do with problem domain then implementation language. I write generic code in C# most days at the moment – jk. Mar 20 '13 at 14:22
  • Yes, in some problem domains generics are common, but the likelihood of finding yourself working in one of those domains is still rare, and obviously the OP isn't. However, I can tell you've never programmed in Ada. Ada uses different types for *everything*, even array indices, and strongly enforces them. Idiomatic Ada is essentially impossible without generics, no matter your domain. – Karl Bielefeldt Mar 20 '13 at 14:52
  • I agree. Most generics code has been written by Microsoft and sits in the .net framework. I've never needed to write new generics code. – kirk.burleson Aug 07 '15 at 13:05
1

As Microsoft says (and others have said in the comments), the most common place to use generics is when you want to define an operation on a list of objects, but don't care too much about the specific types of the objects in the list.

The classic example is sorting a list.


One code smell that possibly indicates the use of generics may improve matters is (from Jeff Atwood):

enter image description here

Peter K.
  • 3,828
  • 1
  • 23
  • 34