I love generics, but it can get tricky. You might want to return null, but aren’t allowed to do so. The problem is that you can’t return null, since the type used might be a reference type or a value type,- and value types can not be null. There are a few ways to solve this:
1. Return the default(T) keyword, “The default keyword, will return null for reference types and zero for numeric value types. For structs, it will return each member of the struct initialized to zero or null depending on whether they are value or reference types” – MSDN
2. You can add a restriction to the method so only reference types are allowed by adding where T : class
3. If you want to use structs then restrict the method to only allow structs and make T nullable
How do you do, and what would your recommend? Any best practices here?
static T GenericMethod<T>(int id)
static T GenericMethod1<T>(int id) where T : class
static T? GenericMethod2<T>(int id) where T : struct