class Program
{
class Ad
{
public string _name { private get; set; }
}
public static void Main()
{
Ad ad = new Ad();
Console.WriteLine(ad._name = "Name");
}
}
Code output : "Name" , but _name field's get is private. Why I don't get an error?
I kind of know what you're trying to do. I guess your code is like this:
class Program
{
class Ad
{
public string _name { private get; set; }
}
public static void Main()
{
Ad ad = new Ad();
Console.WriteLine(ad._name = "Name");
Console.ReadLine();
}
}
Of course it will work, since you're not actually calling the get of ad._name.
Try this and you'll see:
class Program
{
class Ad
{
public string _name { private get; set; }
}
public static void Main()
{
Ad ad = new Ad();
ad._name = "Name";
Console.WriteLine(ad._name);
Console.ReadLine();
}
}
You'll get the following error: "Error 1 The property or indexer 'ConsoleApplication7.Program.Ad._name' cannot be used in this context because the get accessor is inaccessible ... "
Why I don't get an error?
Because you're writing the result of the assignment . The code string result = ad._name = "Name"
will store the result of ad._name = "Name"
in the result
variable, which is "Name".
So you're not calling the getter, like @Jon addresses .
See 7.13.1 Simple assignment :
The result of a simple assignment expression is the value assigned to the left operand . The result has the same type as the left operand and is always classified as a value.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.