Lamloumi Afif
Lamloumi Afif

Reputation: 9081

Value and reference type in generic type implementation

I searched about generic type in C# and I made this conclusion:

  1. All reference types are based on Class
  2. All value types are based on struct
  3. The main differences between struct and class, apart the global differences between value and reference type, are :
  1. There are six basic implementations of a generic type:
  • Where T: class ==>the generic parameter must be a reference type

  • Where T:classA ==>the generic parameter must be an instance of the class classA

  • Where T:InterfaceA ==> the generic parameter must implement the interface InterfaceA

  • Where T:New() ==> the generic parameter must be a class + have a default empty constructor

  • Where T:U ==> the generic parameter must be derived the class U or implement the interface U

  • Where T: struct ==> the generic parameter must be a value type

So I need to know:

  1. If my conclusion is correct?
  2. I can't understand the difference between :
  • where T: New() ==> class with empty constructor

  • where T: class, New() ==> class with empty constructor

Why the second form is used? Why not just use the first one?

Upvotes: 6

Views: 2619

Answers (3)

Jon Hanna
Jon Hanna

Reputation: 113242

The struct can not contain an empty constructor(without arguments).

Not true. The struct will always have a parameterless constructor. You are not however allowed to change it from the default parameterless constructor that you get automatically.

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500225

What you're describing are generic constraints.

Where T:New() ==> the generic parameter must be a class + have a default empty constructor

No, that just says "the type argument must have a parameterless constructor". That actually includes all value types. Even though you couldn't declare your own parameterless constructors for structs before C# 6, you could always call them. For example:

Guid guid = new Guid();

So if you have:

public void Foo<T>() where T : new()

it's perfectly valid to call

Foo<Guid>();

Upvotes: 10

Servy
Servy

Reputation: 203821

The generic constraint new() means that the type has a parameterless constructor. That type could be either a struct or a class. structs cannot provide a custom parameterless constructor, that is because all structs have a parameterless constructor already provided for them, with a default behavior that they cannot change. It doesn't mean that structs can never be created with a parameterless constructor.

Upvotes: 2

Related Questions