D.R. D.R. - 11 days ago 5
C# Question

Distinguish between property is protected and setter is protected

Is there a way to determine the setter visibility difference of:

public Prop { get; protected set; }
protected Prop { get; set; }


using Reflection? Or are those equivalent in regards to C# Reflection?

Answer

No, the two setters are identical.

The definitive way to verify this is to look at the IL generated for the two variants. I compiled a little test with the following two properties:

  public    int Prop  { get; protected set; }
  protected int Prop2 { get; set; }

And then I disassembled it. The IL is identical for the setters for both properties, save for the difference in their names (Prop vs Prop2):

.method family hidebysig specialname instance void 
        set_Prop(int32 'value') cil managed
{
  .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) 
  // Code size       8 (0x8)
  .maxstack  8
  IL_0000:  ldarg.0
  IL_0001:  ldarg.1
  IL_0002:  stfld      int32 ConsoleApplication1.Program::'<Prop>k__BackingField'
  IL_0007:  ret
} // end of method Program::set_Prop
.method family hidebysig specialname instance void 
        set_Prop2(int32 'value') cil managed
{
  .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) 
  // Code size       8 (0x8)
  .maxstack  8
  IL_0000:  ldarg.0
  IL_0001:  ldarg.1
  IL_0002:  stfld      int32 ConsoleApplication1.Program::'<Prop2>k__BackingField'
  IL_0007:  ret
} // end of method Program::set_Prop2

I would say that this is consistent with expectations: both setters have identical visibilities, so they should appear identical to the compiler and run-time environment.