When should we use the new () keyword when inheriting from a common class?

I read a tutorial on a general class, it has this code:

public class ValidationBase {
  public virtual bool IsValidName(string name) {
    return name.Length > 5;
  }
}

 public class LogicBase<T> where T : ValidationBase, new() {
    private T _Validations = default(T);
      public T Validations {
        get {
          if (_Validations == null) {
            _Validations = new T();
           }
        return _Validations;
          }
       set { _Validations = value; }
      }
}

he said that:

The new keyword creates an instance of the DataModelBase class by default, if for T

no specific type specified

I really don't understand when should we use the keyword new()?

NOTE: if you are editing the code above:

 public class LogicBase<T> where T : ValidationBase

instead

 public class LogicBase<T> where T : ValidationBase, new()

what will happen

+4
source share
4 answers

When specifying a general class new(), it acts as a type constraint T.

In this case, new()declares that the type Tshould be a class with an open constructor without parameters.

For instance:

public class MyGenericClass<T> where T : new()
{
}

public class MyClass
{
    public MyClass()
    {
    }
}

public class MyClass2
{
    public MyClass2(int i)
    {
    }
}

class Program
{
    static void Main(string[] args)
    {
        // OK!
        MyGenericClass<MyClass> c1 = new MyGenericClass<MyClass>();

        // Gives the error:
        // 'MyClass2' must be a non-abstract type with a public parameterless
        // constructor in order to use it as parameter 'T' in the generic type
        // or method 'MyGenericClass<T>'
        MyGenericClass<MyClass2> c2 = new MyGenericClass<MyClass2>();
    }
}

, T new T(). , T . where T: new() T .

:

if (_Validations == null) {
    _Validations = new T();
}

T. T , T new MyType().

+4

New T() T , . , new() .

+2

LogicBase , T ValidationBase LogicBase ValidationBase. new() .

, , ValidationBase .

, , , ValidationBase , LogicBase , LogicBase , .

+2

T:

if (_Validations == null) {
    _Validations = new T();
}

T - , , T . , , , LogicBase<T>, .

You guarantee this by using a type constraint newin your class definition. This ensures that wherever you confirm T(for example, when creating or creating from LogicBase<FooBar>), the type argument provided for T(in the previous examples FooBar) has an empty constructor. If a suitable constructor is not available, you will get a compiler error.

+1
source

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


All Articles