Value and reference type when implementing a type type

I searched around generic type in C# and I came to this conclusion:

  • All reference types are based on Class
  • All value types are based on struct
  • The main differences between structure and class, in addition to the global differences between value and reference type, are as follows:

    • No inheritance in struct

    • A structure cannot contain an empty constructor (without arguments)

  • There are six main basic implementations of the generic type:
  • Where T: class ==> the general parameter must be a reference type

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

  • Where T: InterfaceA ==> the general parameter should implement InterfaceA

  • Where T: New () ==> the general parameter must be class +, have an empty default constructor

  • Where T: U ==> the general parameter must be inferred by the class U or implement the U interface

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

So I need to know:

  • If my conclusion is correct?
  • I can not understand the difference between:
  • where T: New () ==> a class with an empty constructor

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

Why is the second form used? Why don't we just use the first?

Thanks,

+6
source share
3 answers

What you describe are general limitations.

Where T: New () ==> the general parameter must be class +, by default empty Constructor

No, it just says: "The type argument must have a constructor without parameters." This actually includes all types of values. Even if you could not declare your own constructors without parameters for structures prior to C # 6, you can always call them. For instance:

 Guid guid = new Guid(); 

So, if you have:

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

this is absolutely true for calling

 Foo<Guid>(); 
+10
source

The general restriction of new() means that the type has a constructor with no parameters. This type can be either a structure or a class. structs cannot provide a custom constructor without parameters, that is, because all structures have a constructor already created without parameters with default behavior that they cannot change. This does not mean that structures can never be created using a constructor without parameters.

+2
source

A string cannot contain an empty constructor (without arguments).

Not true. A structure always has a constructor without parameters. However, you are not allowed to change it from the constructor without parameters, which you get automatically.

+1
source

Source: https://habr.com/ru/post/986778/


All Articles