Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regarding the use of new Constraint in c#

Tags:

c#

i never use new Constraint because the use is not clear to me. here i found one sample but i just do not understand the use. here is the code

class ItemFactory<T> where T : new()
{
    public T GetNewItem()
    {
        return new T();
    }
}

public class ItemFactory2<T> where T : IComparable, new()

{
}

so anyone please make me understand the use of new Constraint with small & easy sample for real world use. thanks

like image 883
Thomas Avatar asked Jan 25 '12 12:01

Thomas


People also ask

What is new () constraint in C#?

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

What is the purpose of the class constraint on a type parameter?

Object, you'll apply constraints to the type parameter. For example, the base class constraint tells the compiler that only objects of this type or derived from this type will be used as type arguments. Once the compiler has this guarantee, it can allow methods of that type to be called in the generic class.

What are generic classes in C#?

Generic is a class which allows the user to define classes and methods with the placeholder. Generics were added to version 2.0 of the C# language. The basic idea behind using Generic is to allow type (Integer, String, … etc and user-defined types) to be a parameter to methods, classes, and interfaces.


1 Answers

This constraint requires that the generic type that is used is non-abstract and that it has a default (parameterless) constructor allowing you to call it.

Working example:

class ItemFactory<T> where T : new()
{
    public T GetNewItem()
    {
        return new T();
    }
}

which obviously now will force you to have a parameterless constructor for the type that is passed as generic argument:

var factory1 = new ItemFactory<Guid>(); // OK
var factory2 = new ItemFactory<FileInfo>(); // doesn't compile because FileInfo doesn't have a default constructor
var factory3 = new ItemFactory<Stream>(); // doesn't compile because Stream is an abstract class

Non-working example:

class ItemFactory<T>
{
    public T GetNewItem()
    {
        return new T(); // error here => you cannot call the constructor because you don't know if T possess such constructor
    }
}
like image 161
Darin Dimitrov Avatar answered Sep 30 '22 02:09

Darin Dimitrov