Generics used in struct vs class

Suppose we have the following struct definition that uses generics:

 public struct Foo<T> { public T First; public T Second; public Foo(T first) { this.First = first; } } 

Compiler says

'Foo.Second' must be fully assigned before control is returned to the caller

However, if Foo is a class, it compiles successfully.

 public class Foo<T> { public T First; public T Second; public Foo(T first) { this.First = first; } } 

Why? Why does the compiler treat them differently? Moreover, if the constructor is not defined in the first Foo , then it compiles. Why is this behavior?

+7
source share
4 answers

This is because the compiler rule provides that all fields in the structure must be assigned before any constructor leaves the control.

You can make your code work by doing this:

 public Foo(T first) { this.First = first; this.Second = default(T); } 

Also see Why should I initialize all fields in my C # structure using an unnamed constructor?

+12
source

This is a requirement of structures in general - it has nothing to do with generics. Your constructor must assign a value to all fields.

Note that the same error occurs here:

 struct Foo { public int A; public int B; public Foo() { A = 1; } } 
+9
source

Since in C # there is a rule for which all fields for structs (inline or in constructor) should be assigned. This is due to the structural nature. It has nothing to do with generic or not common.

+1
source

Other answers correctly explain the behavior, but neglect to mention the second part of your question, so here it is for completion.

If you do not explicitly define a constructor, the compiler will create a default constructor that assigns default values ​​(for example, null for objects, 0 for numbers, etc.) for each field.

0
source

All Articles