1
struct MYSTRUCT
{
 public int x;
 public int y;
 public int z;
}

        MYSTRUCT s;
        s.x = 2;
        s.y = 4;
        Console.WriteLine(s); //error on this line

This generates a compiler error

error CS0165: Use of unassigned local variable 's'

It raises a couple of questions - firstly since a struct is a value type and non-nullable, why does s need to be initialized? Secondly, why is assigning to s.x and s.y OK and only the final line generates the error?

I'm not asking how to fix my code, it just made me interested why a struct must be assigned/initialized as a value type?

(note: MYSTRUCT only has simple byte/int members)

Mr. Boy
  • 60,845
  • 93
  • 320
  • 589
  • 2
    What does MYSTRUCT look like? – nicomp May 13 '20 at 15:25
  • Structs do have default values... they can't be `null`. But C# still expects you to initialize them and will complain if you don't. You initialized `s.x` and `s.y`, but not `s` itself. As for the "why", the only people who could tell you are on the language team at MS. – Joel Coehoorn May 13 '20 at 15:30
  • The idea with that error is that forcing someone to explicitly state they want a variable initialized to the default is not that bad of a thing to force people to do and it will catch bugs when you forgot to initialize it to an actual value. Since it's a struct I believe those assignments don't matter unless you actually use the variable, thus that's why the error is on the `Console.WriteLine`. And I'm guessing they don't do any special handling for this case as mutable structs are a bad idea to begin with. – juharr May 13 '20 at 15:38
  • 4
    Does `MYSTRUCT` have other instance fields besides `x` and `y`? – Joe Sewell May 13 '20 at 15:44

1 Answers1

4

You are misunderstanding the error you are getting. Structs are considered to be definitely assigned if all instance fields are definitely assigned. This is perfectly valid:

struct A
{
    public int i;
}

A a;
a.i = 1;
Console.WriteLine(a); //no error, a is considered to be definitely assigned.

But this isn't:

struct A
{
    public int i;
    public int j;
}

A a;
a.i = 1;
Console.WriteLine(a); //a is not definitely assigned because a.j isn't.

The error is similar to the one you get if you do not initialize members inside a custom constructor:

struct A
{
    public A(int i)
    {
        this.i = i;
    } //error, j is not assigned.

    public int i;
    public int j;
}

In your case, MYSTRUCT must have instance fields that are not being correctly initialized or must be initialized through a propery setter.

In short, don't worry about this issue because you can really only initialize value types this way if they:

  1. are mutable
  2. expose directly all instance fields (not through properties)

Both are generally considered bad practices so you should probably run away from any value type you encounter that fit in these two categories.

InBetween
  • 32,319
  • 3
  • 50
  • 90