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?
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With