Assume that 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;
}
}
The compiler says
'Foo.Second' must be fully assigned before control is returned to the caller
However, if Foo
is a class, then it compiles successfully.
public class Foo<T>
{
public T First;
public T Second;
public Foo(T first)
{
this.First = first;
}
}
Why? Why the compiler treats them differently? Moreover if no constructor is defined in the first Foo
then it compiles. Why this behaviour?
C# permits classes, structs, interfaces and methods to be parameterized by the types of data they store and manipulate, through a set of features known collectively as generics.
In addition to generic classes, you can also create a generic struct. Like a class, the generic struct definition serves as a sort of template for a strongly-typed struct.
Use generic types to maximize code reuse, type safety, and performance. The most common use of generics is to create collection classes. The . NET class library contains several generic collection classes in the System.
Generics allow you to define the specification of the data type of programming elements in a class or a method, until it is actually used in the program. In other words, generics allow you to write a class or method that can work with any data type.
That's a requirement of structs in general -- it has nothing to do with generics. Your constructor must assign a value to all fields.
Note the same error happens here:
struct Foo
{
public int A;
public int B;
public Foo()
{
A = 1;
}
}
That is because a compiler rule enforces that all fields in a struct must be assigned before control leaves any constructor.
You can get your code working by doing this:
public Foo(T first)
{
this.First = first;
this.Second = default(T);
}
Also see Why Must I Initialize All Fields in my C# struct with a Non-Default Constructor?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With