The image below shows the Main()
class and the code I have written in it.
The following image shows the Car() class and the code I have written in it.
The error that I face is as follows:
Car.model
is inaccessible due to its protection level
Car.color
is inaccessible due to its protection level
In the Car class, the private variables model and color have been given the property by the set()
and get()
methods and then passed into the class constructor, the object of this constructor is initialized in the Main()
but on the line where I print the model and color of the car it gives the above mentioned errors.
I understand that model and color variables are private but I have passed them specifically though the get()
and set()
methods so that there values can be changed but that is not the case here.
I was expecting it to work but this error has me scratching my head. Is it because the variables are being initialized through the constructor and specifically when I am creating the object? or is there some other reason to it? How can I rectify it?
From what I have learned so far this way should work, there should be no issue if you are initializing a private variable by get and set methods when creating the object.
CodePudding user response:
You want to show the model of a car. For that, you defined a property. But you want to get the value from the field which is private.
So you have just to write Ford.Model
instead of Ford.model
. Same for color: Ford.Color
instead of Ford.color
.
Important:
Your fields are backing fields. This fields are set in your constructor. And to get the value of them, you need to return them in your properties (I named the private field _color
because this is a naming convention for private fields):
private string _color;
public string Color
{
get => _color;
set => _color = value;
}
I think you should read some basic information about properties. For example on this site: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/properties