Generics are a .Net 2.0 feature that essentially let you abstract out type. You can learn a lot about generics on MSDN.
One problem that generics can solve is how to have a method dynamically return a given type. For example, in the snippet below, the method GetData returns different types depending on what you pass in - either a double or an Int32. This is useful for creating a generalized method to parse out (and potentially validate) data. Note that the consumer of the GetData method need not deal with conversion - it receives a strongly typed value.
While this is just a trivial snippet, it's a nice demo of one of the features of generics.
public void DemoGenerics()
int i = GetData
double d = GetData
public static T GetData
string strType = typeof(T).Name;
throw new Exception("Type not supported");
Living in Chicago and interested in a great company? Check out the careers at Paylocity.
Post a Comment