0

There are two methods which does the same task. The only difference in them is one has "new()" and other does not have.

The methods are:

Method 1:

public void Method1<T>(BaseReportContent content) where T : BaseReportContent, new()
{
   //Codes
}

Method 2:

public void Method2<T>(BaseReportContent content) where T : BaseReportContent
{
   //Codes
}

What is the benefits of using one over another?

Let me know if more information required to make this question more precise.

Bijay Yadav
  • 928
  • 1
  • 9
  • 22

2 Answers2

4

The new() constraint will allow you to create a new T. For instance

public void Method1<T>(BaseReportContent content) where T : BaseReportContent, new()
{
    var myT = new T();
}

Note : There are caveats

new constraint (C# Reference)

The new constraint specifies that any type argument in a generic class declaration must have a public parameterless constructor. To use the new constraint, the type cannot be abstract.


Additional Resources

You can find more information on generic constraints here

Constraints on type parameters (C# Programming Guide)

Constraints inform the compiler about the capabilities a type argument must have. Without any constraints, the type argument could be any type. The compiler can only assume the members of System.Object, which is the ultimate base class for any .NET type. For more information, see Why use constraints. If client code tries to instantiate your class by using a type that is not allowed by a constraint, the result is a compile-time error. Constraints are specified by using the where contextual keyword. The following table lists the seven types of constraints:

Lastly, if you need to create something that need constructor parameters, you can use

Activator.CreateInstance Method

Creates an instance of the specified type using the constructor that best matches the specified parameters.

TheGeneral
  • 79,002
  • 9
  • 103
  • 141
0

The first method uses the new constaint, which means you can write:

public void Method1<T>(BaseReportContent content) where T : BaseReportContent, new()
{
    var foo = new T();
}

The second method does not have this constraint, which means you cannot write such code.

Ian Kemp
  • 28,293
  • 19
  • 112
  • 138