Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generics used in struct vs class

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?

like image 229
Sleiman Jneidi Avatar asked Dec 05 '12 20:12

Sleiman Jneidi


People also ask

Can struct have generic C#?

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.

Can struct be generic?

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.

When would you use generics in your code?

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.

Why generics are used in C#?

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.


2 Answers

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;
    }
}
like image 44
Jon B Avatar answered Oct 03 '22 02:10

Jon B


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?

like image 113
driis Avatar answered Oct 03 '22 01:10

driis