Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What means where S : new() in c# [duplicate]

Tags:

c#

generics

In the following code I do not know what means " where S : new() " part. What is the keyword to find more info in Google ?

    public virtual void Print<S, T>() 
        where S : new() 
    { 
        Console.WriteLine(default(T)); 
        Console.WriteLine(default(S)); 
    } 
like image 646
user1309871 Avatar asked Jul 06 '13 14:07

user1309871


People also ask

What is the meaning of \n in C?

In C, all escape sequences consist of two or more characters, the first of which is the backslash, \ (called the "Escape character"); the remaining characters determine the interpretation of the escape sequence. For example, \n is an escape sequence that denotes a newline character.

What is %s in printf?

%s and string We can print the string using %s format specifier in printf function. It will print the string from the given starting address to the null '\0' character. String name itself the starting address of the string. So, if we give string name it will print the entire string.

Does new work in C?

There's no new / delete expression in C.


1 Answers

The new() constraint means that the particular generic parameter is required to have a default constructor (i. e. a constructor with no parameters).

The purpose of this is typically to allow you to type-safely construct new instances of generic parameter types without resorting to reflection/Activator.CreateInstance.

For example:

public T Create<T>() where T : new()
{
    // allowed because of the new() constraint
    return new T();
}

For more information, check out http://msdn.microsoft.com/en-us/library/sd2w2ew5%28v=vs.80%29.aspx.

As far as a google search term, I'd try "c# new() constraint".

like image 105
ChaseMedallion Avatar answered Oct 17 '22 00:10

ChaseMedallion