What is the purpose of new () in defining the general?

I'm trying to understand generics. Here is an example of one of them:

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. First, what is the purpose of the new () in the definition. My other question is: how can I use this common one. Here is an example:

 _tableStorage.CreateTableIfNotExist<MembershipRow>(_tableName); 

But I do not understand. What is the purpose of this common? Can't I do the same thing without the general?

 _tableStorage.CreateTableIfNotExist("MyNewTable"); 
+4
source share
3 answers

This is a general type restriction, indicating that the type should have an open constructor with no parameters.

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

Further reading .

The main use of this is to allow generic code to instantiate T , not default(T) you often see. Unfortunately, there is no support for constraints for anything other than an open constructor without parameters when it comes to constructor constraints.

Update: looking at the updated code, the general one is not used, so in this case it has no purpose. A common tactic for generics in extension methods is to support common 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, do not specify a type restriction, this will only work if the type restriction can be inferred by the compiler based on usage ... I'm not sure what will happen in your case, but I would assume that it will not compile.

+9
source

This is a new limitation . This means that only types that have an open constructor that takes no arguments can be a type argument for a generic type.

so a class like this:

 public class Xyz{ public string HelloWorld; } 

can be used with this function, but this class:

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

could not, because he does not have the required constructor.

+1
source

T will be replaced by the type specified in <> , which means that if you exit new , it will provide a Type , not an instance of InitializeTableSchemaFromEntity

+1
source

Source: https://habr.com/ru/post/1386473/


All Articles