Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Type pattern: definite assignment false positive for struct that has only reference type properties and is declared in another assembly #38723

Closed
HellBrick opened this issue Sep 17, 2019 · 2 comments

Comments

@HellBrick
Copy link

Version Used:
Visual Studio 16.2.5
MSBuild 16.2.37902+b5aaefc9f
csc.exe 3.2.1-beta4-19408-03

Steps to Reproduce:
You need two assemblies for this, Lib and App, where App references Lib.

// Lib
namespace Lib
{
	public struct StructWithStringProp
	{
		public string Text { get; set; }
	}
}

// App
namespace App
{
	internal class CallSites
	{
		private static string ExternalStringPropCallSite(Lib.StructWithStringProp? nullable)
		{
			bool flag = nullable is Lib.StructWithStringProp notNull;
			return flag ? notNull.ToString() : "";
		}
	}
}

Expected Behavior:
error CS0165: Use of unassigned local variable 'notNull'

Actual Behavior:
The code compiles.

Additional information:
If you make any of the following changes, the code stops compiling and the expected error appears:

  • replace struct's property with a field
  • change struct's property type from string to, let's say, int
  • move struct declaration from Lib to App

You can check out a solution that illustrates all these permutations and their effect on the compiler behavior here.

@jcouv
Copy link
Member

jcouv commented Sep 17, 2019

I suspect this is a known issue due to the struct being empty. That said, I'm not sure why this would only affect an empty struct defined in metadata (as opposed to the same compilation/source).
Tagging @gafter to confirm.

@gafter
Copy link
Member

gafter commented Sep 17, 2019

This is an intentional behavior. See also #30194 where we propose to fix this intentionally broken behavior. The struct contains only a private (in this case compiler-generated) field of a reference type, so (due to the intentional behavior of the compiler) it is ignored for the purposes of definite assignment when imported from an assembly.

@gafter gafter closed this as completed Sep 17, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants