I'm getting the following error :
"Property does not exist in the current context".
I checked on StackOverflow the usual causes of this, but I have made no one of the mistakes presented. (at least none of those I understood ^^). I am working with Microsoft Visual Studio 2015
Here is my code :
namespace ConsoleApplication5 { public class Voiture { public int Vitesse { get; set; } public Voiture() { Vitesse = 5; } public string Marque { get { throw new System.NotImplementedException(); } set { } } } }
and in another file
namespace ConsoleApplication5 { public class Audi : Voiture { public void Deraper() { Console.WriteLine("Vroooouum !!"); } this.Marque = "Audi"; } }
If instead of
this.Marque I use
Voiture.Marque, I get the same problem. As you can see, the namespaces are OK. Any idea of what is going on ?
1) You are not allowed to access and initialize inherited properties outside a method body. You are only allowed to declare new properties or fields there.
2)
Marque is of type
int and you cannot assign a
string to it
3) your setter of
Marque is empty so this will have no effect
Solutions:
1) Move the access of
this.Marque into the constructor or a method body!
2) change either the type of
Marque to
string or the value that you assign to it to an
int
3) add an extra private field and rewrite the setter (and the getter) in the following way:
private int marque; public int Marque { get { return marque; } set { marque = value; } }
For more information on how to use properties you can check these links out:
EDIT:
If instead of
this.MarqueI use
Voiture.Marque, I get the same problem.
This is because the first problem is still valid. If you would do this inside a method body you would get an additional problem! Because
Marque is not
static, so you cannot use it by calling it with the class name. You would need an instance of an object of type
Voiture