Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class library allow use unassigned structures

I have my structure:

public struct MyType
{
    private string value;

    // Methods
    // ... (ToString overrided too)
}

If I put the structure in Program.cs or another File.cs, and I create a variable as MyType (my structure) and I try to use it, the result is an obvious error:

CS0165 Use of unassigned local variable

Example:

MyType a; 
Console.WriteLine(a); // Error: Use of unassigned local variable 'a'

MyType b = new MyType(); 
Console.WriteLine(b); // Prints the default value (an empty string)

The problem is when I put the structure in a class library (either in another project, or from a NuGet package) and I use it from Program.cs:

MyType a;
Console.WriteLine(a); // No error: prints an empty string

Why is this happening?

like image 232
Joe Avatar asked Apr 28 '16 00:04

Joe


Video Answer


1 Answers

As far as I can tell this is by design. See this issue on GitHub:

'error CS0165: Use of unassigned local variable' is not produced for structs with a private reference type field from a different assembly

This issue has been closed and labeled as "Resolution-By Design".

In that issue, gafter has this to say:

This was a very painful but intentional decision. This duplicates the (buggy) behavior of the previous compiler. I strongly recommend you add the compiler flag /features:strict to get the correct, specification-required (but not backward-compatible) behavior.

like image 66
reduckted Avatar answered Oct 16 '22 22:10

reduckted