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?
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.
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