(Thanks everyone for the answers, here is my refactored example, in turn another StackOverflow question about the Single Responsibility Principle.)
Coming from PHP to C#, this syntax was intimidating:
container.RegisterType<Customer>('customer1');
until I realized it expresses the same thing as:
container.RegisterType(typeof(Customer), 'customer1');
as I demonstrate in the code below.
So is there some reason why generics is used here (e.g. throughout Unity and most C# IoC containers) other than it just being a cleaner syntax, i.e. you don’t need the typeof() when sending the type?
using System; namespace TestGenericParameter { class Program { static void Main(string[] args) { Container container = new Container(); container.RegisterType<Customer>('test'); container.RegisterType(typeof(Customer), 'test'); Console.ReadLine(); } } public class Container { public void RegisterType<T>(string dummy) { Console.WriteLine('Type={0}, dummy={1}, name of class={2}', typeof(T), dummy, typeof(T).Name); } public void RegisterType(Type T, string dummy) { Console.WriteLine('Type={0}, dummy={1}, name of class={2}', T, dummy, T.Name); } } public class Customer {} } //OUTPUT: //Type=TestGenericParameter.Customer, dummy=test, name of class=Customer //Type=TestGenericParameter.Customer, dummy=test, name of class=Customer
A primary reason is the type safety at compile time. If you are passing two
Typeobjects you are placing the responsibility at the developer instead of the compiler.This is also why many IoC containers utilizes it, as your compiler will complain if an concrete type isn’t inheriting the abstract type.
This code will only work if
TConcreteis implementing or inheritingTAbstract. If this method took twoTypeparameters, your method should validate this relationship.