Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

properties

I am setting the property of a class like that

public string Name { get; set; }

But i can also set the property like that

public string Name { get; private set; }

I want to know the difference between these? and what scope they have?

like image 737
Talha Avatar asked Dec 20 '22 21:12

Talha


1 Answers

It means you cannot set this property from class instance. Only member of same class can set it. Hence for outsiders this property becomes 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 will set value in Name2 but setting value in Name2 directly is not possible.

and what scope they have?

Since Name1 and Name3 property are public so they and their get and set methods are available everywhere.

Name3 is also public but its set is private so property and get method will be available everywhere. Set method scope is limited to class only (private access modifier has scope inside entity where it is defined).

like image 139
Nikhil Agrawal Avatar answered Dec 23 '22 11:12

Nikhil Agrawal