1

I am specifying a public property in C# like this:

public bool SuezCanalTransversal {get; set;}

However, it appears that no private member variable is created. For example, if I override the get, and return _suezCanalTransversal; I see that:

"_suezCanalTransversal does not exist in the current context".

It is no problem to simply add the associated private member variables on my own, but I was under the impression that this was now done automatically.

A few questions:

When are private member variables automatically generated for public properties and when are they not?

When a public property such as public bool SuezCanalTransversal{ get; set;} is used, is it correct to assume a private variable: private bool _suezCanalTransversal will be created?

Doug Kimzey
  • 1,019
  • 2
  • 17
  • 32
  • See https://stackoverflow.com/questions/8817070/is-it-possible-to-access-backing-fields-behind-auto-implemented-properties. – Kirk Larkin Aug 27 '17 at 19:42
  • 1
    Possible duplicate of [Is it possible to access backing fields behind auto-implemented properties?](https://stackoverflow.com/questions/8817070/is-it-possible-to-access-backing-fields-behind-auto-implemented-properties) – Patrick Aug 27 '17 at 19:44
  • There is a private variable, but it has a different, compiler-generated name and you cannot access it (except with reflection) You're not supposed to be able to access it; you're supposed to use the property. – Dennis_E Aug 27 '17 at 19:44
  • Sidenote: Do you come from VB .net? In vb its possible to access the private members at designtime targeting to Me."_PropertyName" – Cadburry Aug 27 '17 at 20:09

1 Answers1

7

The compiler generates the backing variable, and you can not rely on any naming convention or pattern that is used to name that backing variable.

The backing variable is only declared at compile time, so you cannot access it in your source code.

If you want to have access to the backing variable, there is only one solution: do not use automatic properties, but declare the properties 'old skool', like this:

private int _suezCanalTransversal;

public int SuezCanalTransversal
{
   { get return _suezCanalTransversal; }
   { set _suezCanalTransversal = value; }
}
Frederik Gheysels
  • 56,135
  • 11
  • 101
  • 154