Nuri Tasdemir
Nuri Tasdemir

Reputation: 9842

Are there any difference between "where : class, new()" and "where : new()"?

In C# while writing a generic class or function, are there any difference between where : class, new() and where : new()? Does new() imply that it is also class?

As I understand from this structs cannot have parameterless constructors

Upvotes: 2

Views: 94

Answers (2)

BoltClock
BoltClock

Reputation: 723729

Does new() imply that it is also class?

No, new() just means the type has a public default constructor. Both classes and structs can have such constructors. Neither constraint implies the other in any way.

As I understand from this structs cannot have parameterless constructors

The keyword in that document is "explicit", i.e. a constructor that you declare in code. A default constructor is an implicit parameterless constructor that's created by the compiler for a type when it has no explicit constructor definitions, with or without parameters.

Upvotes: 4

Trevor Pilley
Trevor Pilley

Reputation: 16393

The new() constraint on a generic class or method means that T must have a default constructor but doesn't care whether T is a class or struct

Upvotes: 1

Related Questions