Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of new() when defining a generic?

Tags:

c#

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");
like image 221
Samantha J T Star Avatar asked Dec 22 '22 04:12

Samantha J T Star


2 Answers

It is a generic type constraint stating that the type must have a public parameterless constructor.

myCloudTableClient.CreateTableIfNotExist<TypeWithPublicParameterlessConstructor>("Customers");

Further reading.

The main use of this is to allow the generic code to construct an instance of T, as opposed to default(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.

public static bool Equals<T>(this T self, T other) where T : IEquatable<T>
{
    return self.Equals(other);
}

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.

like image 169
Adam Houldsworth Avatar answered Dec 23 '22 18:12

Adam Houldsworth


It's the new constraint. It means only types that have a public constructor that takes no arguments can be the type argument for the generic type.

so a class like this:

public class Xyz{
  public string HelloWorld;
}

could be used with that function, but this class:

public class Abc{
  pulblic string HelloWorld;
  pulbic Abc(string hello){
    HelloWorld = hello;
  } 
}

could not, as it doesn't have the required constructor.

like image 42
Russell Troywest Avatar answered Dec 23 '22 17:12

Russell Troywest