Why different access modifiers are not set for an automatically implemented property in C #

Why is an invalid expression below? I know how to resolve errors, but I wonder why this statement can now be explained.

public int Number {public get;protected set; } 

I have no use case or application to clarify why this should be allowed. But the compiler throws 2 errors:

 Error 2 The accessibility modifier of the 'LambdaExpressions.Program.Person.Number.get' accessor must be more restrictive than the property or indexer 'LambdaExpressions.Program.Person.Number' LambdaExpressions\LambdaExpressions\Program.cs 66 39 LambdaExpressions 

and

 Error 1 Cannot specify accessibility modifiers for both accessors of the property or indexer 'LambdaExpressions.Program.Person.Number' LambdaExpressions\LambdaExpressions\Program.cs 66 24 LambdaExpressions 
+4
source share
3 answers

Since you already need to specify one of the modifiers first:

 public int Number {public get;protected set; } //^ //here 

What will this modifier change if you have modifiers for both accessories?

those. imagine an even stranger example:

 public int Number {protected get;protected set; } 

Exactly what part or concept of Number now public ?

In the @dash comments from MSDN :

By default, these accessors have the same visibility or access level: the property of the property or indexer to which they belong

You can use access modifiers only if the property or indexer has both set and accesses. In this case, the modifier is allowed on only one of the two accessories .

( My emphasis )

+24
source

Since providing a modifier for accessing a property not only automatically passes it to get and set , but also implies a restriction, which: even if any modifier applied to them should be more restrictive so that one that is defined in the property itself.

With that in mind, you can do

 public int A { get; private set; } 

but you cannot do (by language design)

  //both modifer can not have be more restrictive then property itself //non sence public int A { protected get; private set; } 

yo can't do

  //one of modifiers is less restrictive //again non sence protected int A { public get; set; } 
+4
source

Your example is superfluous. The access modifier is already publicly available, and specifying it again is pointless.

However, the real problem is that C # allows you to specify more restrictive modifiers, so the following code is illegal:

 private int Number {public get; set;} 

This has a side effect, also being illegal if you specify the same level (i.e. public and open). This should be more restrictive.

You can also specify only one modifier, because otherwise it is pointless to put an access modifier in this property.

 public int Number {protected get; private set;} // How is it public? 
0
source

Source: https://habr.com/ru/post/1487823/


All Articles