Fredou
Fredou

Reputation: 20100

what is the automatic variable name of an auto-implemented properties

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};
     }

Upvotes: 4

Views: 1693

Answers (5)

jeroenh
jeroenh

Reputation: 26782

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";
}

Upvotes: 0

Eric Lippert
Eric Lippert

Reputation: 659964

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.

Upvotes: 3

Mike Mooney
Mike Mooney

Reputation: 11989

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

Upvotes: 0

JaredPar
JaredPar

Reputation: 754565

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.

Upvotes: 11

Related Questions