Skip to content

Union case types not checked for accessibility consistencyΒ #86583

Description

@amal-stack

Version Used:

  • .NET version: 11.0.100
  • Compiler version: '5.12.0-1.26452.1 (e42c0e4)'
  • Language version: 15.0.

If there is a union type with a private inner type:

public union Outer(string, Outer.Inner)
{
    private class Inner;
}

It compiles with no diagnostic. The lowered code contains a public constructor whose parameter type is the private nested class:

[CompilerGenerated]
public Outer([Nullable(1)] Inner value)
{
	<Value>k__BackingField = value;
}

Switching over an instance of it using a switch expression outside the declared type where Inner is inaccessible:

static string Describe(Outer outer) => outer switch
{
    string s    => "string",
};

reports:

CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern 'Outer.Inner' is not covered.

However, adding it is not possible:

static string Describe(Outer outer) => outer switch
{
    string s    => "string",
    Outer.Inner i => "inner"
};

as this reports:

CS0122: 'Outer.Inner' is inaccessible due to its protection level

and

CS8121: An expression of type 'Outer' cannot be handled by a pattern of type 'Outer.Inner'

The same happens with an internal case type switched over from another assembly.

.NET Lab

Expected Behavior:
As per the docs, a union declaration is lowered to a struct declaration witha public constructor for each of the case_types.

For a constructor written in source, a parameter type less accessible than the constructor triggers a CS0051:

Inconsistent accessibility: parameter type 'type' is less accessible than method 'method'.

I'd expect this declaration to be reported the same way.
If it's intended that case types can be less accessible than the union, I'd expect that to be documented, along with how consumers should write an exhaustive switch.

Actual Behavior:

  • The declaration compiles with no errors, and the generated public constructor has a less accessible parameter type.
  • A consumer's switch reports CS8509 naming the inaccessible type: "the pattern 'Outer.Inner' is not covered". Adding a case for it reports CS0122, so the warning can't be fixed by handling the case. (For comparison, a closed class C with a descendant that isn't visible at the switch site gives the same CS8509 but names the visible base type ("the pattern 'C' is not covered") and this behavior is documented.)
  • The only way to silence CS8509 is a _ or var arm, which swallows all other cases.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions