Type vs Generics

time to read 2 min | 282 words

An interesting post on The Moth on which of the two you should prefer?

  • new Blah<SomeType>();
  • new Blah(typeOf(SomeType));

Personally, I like the first one better, but I can see the benefits of the other one as well. I'm currently have a faint smell regarding this with a method calls that look like this:

Container.Repository<Blog>().Save(blog);

I could've written it the other way, like this:

Container.Repository(typeof(Blog)).Save(blog);

But it's shorter and clearer (to me) the first way, and I can do some compiler time validation on it. Beyond that, even though there are some dynamic stuff going on there, it looks static, and that is important. I'm using this pattern to abstract my whole data acess strategy, and it's working quite well so far. I get different repositories for different types, and I can put custom behaviors during save/load quite easily (validation, business rules, etc).

I'm even using this to get stuff that doesn't come from a database, in a way that is totally transperant to the application. In my opinion, the generic version is better, since it looks like it's part of the language.