I am trying to understand generics. Here’s an example of one:
public static bool CreateTableIfNotExist<T>(this CloudTableClient tableStorage, string entityName)
where T : TableServiceEntity, new()
{
bool result = tableStorage.CreateTableIfNotExist(entityName);
return result;
}
I have a couple of questions. Firstly, what’s the purpose of new() in the definition. My other question is, how can I use this generic. There’s an example here:
_tableStorage.CreateTableIfNotExist<MembershipRow>(_tableName);
But i don’t understand. What really is the purpose of this generic? Can’t I just do the same thing without the generic?
_tableStorage.CreateTableIfNotExist("MyNewTable");
It is a generic type constraint stating that the type must have a public parameterless constructor.
Further reading.
The main use of this is to allow the generic code to construct an instance of
T, as opposed todefault(T)– something you may often see. Unfortunately, there is no constraint support for anything other than a public parameterless constructor, when it comes to constraining on constructors.Update: looking at the code you have updated, the generic isn’t ever used so in this case it has no purpose. A common tactic for generics on extension methods is to support generic extension methods.
Update 2: in your example of not specifying the type constraint, this would only work if the type constraint could be inferred by the compiler based on usage… I’m not sure what would happen in your case, but I’d guess it wouldn’t compile.