The property is set as private or without a private keyword. What is the difference?

I set a property of a class such that

public string Name { get; set; } 

But I can also set a property like this

 public string Name { get; private set; } 

I want to know the difference between the two? and how much do they have?

+4
source share
3 answers

In the case of public string Name { get; private set; } public string Name { get; private set; } public string Name { get; private set; } Using a private set means that the ReadOnly property ReadOnly externally. This is useful when you have a read-only property and I don't want to explicitly declare a fallback variable.

public string Name { get; private set; } public string Name { get; private set; } it is similar:

 private string _Name; public string Name { get { return _Name; } private set { _Name = value; } } 
+3
source

This means that you cannot set this property from an instance of the class. Only a member of the same class can set it. Therefore, for outsiders, this property becomes the read-only property.

 class Foo { public string Name1 { get; set; } public string Name2 { get; private set; } public string Name3 { get { return Name2; } set { Name2 = value; } } 

Then

 Foo f = new Foo(); f.Name1 = ""; // No Error f.Name2 = ""; // Error. f.Name3 = ""; // No Error 

Name3 set the value to Name2 , but the setting value in Name2 is not directly possible.

and how much do they have?

Since the properties Name1 and Name3 are publicly available, therefore they and their get and set methods are available everywhere.

Name3 also publicly available, but its set is private, so the property and get method will be available everywhere. The method range is limited only by the class (the private access modifier has a scope within the object where it is defined).

+5
source

The first one will have the Set and Get methods available from your class. The second method will have Get , available from your class, but the Set method will be available only in your class. This usually means read-only behavior.

+3
source

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


All Articles