4

I'm trying to do this:

public string LangofUser 
    { 
       get 
       { 
          return string.IsNullOrEmpty("how to get value?") ? "English" : "how to get value?"; 
       } 
       set; 
     }

do I have to do this?

string _LangofUser
public string LangofUser 
     { 
       get 
       { 
         return string.IsNullOrEmpty(_LangofUser) ? "English" : _LangofUser; 
       } 
       set { _LangofUser = value};
     }
Fredou
  • 19,848
  • 10
  • 58
  • 113
  • 1
    You have to do it the second way. The first is not possible. – Joel Etherton Sep 27 '11 at 17:05
  • 1
    "what is the automatic variable name of an auto-implemented properties" The backing field is anonymous. That means it doesn't have a name. – BoltClock Sep 27 '11 at 17:07
  • possible duplicate of [C# properties: how to use custom set property without private field?](http://stackoverflow.com/questions/4833635/c-sharp-properties-how-to-use-custom-set-property-without-private-field) – nawfal Jun 03 '13 at 18:07

5 Answers5

11

This mixing of auto-implement and not-auto-implemented properties in C# is not possible. A property must be fully auto-implemented or a normal property.

Note: Even with a fully auto-implemented property there is no way to reference the backing field from C# source in a strongly typed manner. It is possible via reflection but that's depending on implementation details of the compiler.

JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
3

As others have said, don't try to mix automatic and regular properties. Just write a regular property.

If you want to know what secret names we generate behind the scenes for hidden compiler magic, see

Where to learn about VS debugger 'magic names'

but do not rely on that; it can change at any time at our whim.

Community
  • 1
  • 1
Eric Lippert
  • 647,829
  • 179
  • 1,238
  • 2,067
0

If you provide your own implementation of the property, it's not automatic any more. So yes, you need to do create the instance.

Mike Mooney
  • 11,729
  • 3
  • 36
  • 42
0

If you want to keep the automatic property and still have a default value, why don't you initialize it in your constructor?

public class MyClass
{
    public MyClass() { LangOfUser = "English"; }
    public string LangOfUser { get; set; }
}

Since C# 6, you can also set a default value for a property as follows:

public class MyClass
{
    public string LangOfUser { get; set; } = "English";
}
jeroenh
  • 26,362
  • 10
  • 73
  • 104