Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Basic C# property question

Tags:

c#

properties

oop

In C# do properties need to reference private member variables, or can I just declare the properties and use them directly in the class code?

If the former is the best practice, then does that rule out using C# property short-hand? I.e.

public string FirstName { get; set; }
like image 956
alchemical Avatar asked Mar 11 '26 04:03

alchemical


1 Answers

Properties, when implemented like this:

public string FirstName { get; set; }

Automatically create a private member variable (the compiler does this for you), so you don't have to worry about it. This will behave exactly the same as if you do:

private string firstName;
public string FirstName { 
    get { return firstName; }
    set { firstName = value; }
}

There is no reason not to use the automatic properties ( { get; set; } ). The provide the same advantages as making your own private member variable.

In addition, if you later decide you need to do extra processing (for example, if you decide to implement INotifyPropertyChanged in your property setter), you can add this without changing your public API, but putting a backing field in manually.

like image 92
Reed Copsey Avatar answered Mar 12 '26 16:03

Reed Copsey