Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Automatic Properties and public field in C# 3.0

Tags:

c#

c#-3.0

I failed to understand why auto implemented property language feature exist in C# 3.0.

What the difference it is making when you say

public string FirstName;

than

public string FirstName { get; set; }
like image 865
123Developer Avatar asked Aug 01 '09 16:08

123Developer


People also ask

What is the difference between a property and a field in C?

Properties expose fields. Fields should (almost always) be kept private to a class and accessed via get and set properties. Properties provide a level of abstraction allowing you to change the fields while not affecting the external way they are accessed by the things that use your class.

What is the difference between field and properties?

A field is a variable of any type that is declared directly in a class. A property is a member that provides a flexible mechanism to read, write or compute the value of a private field. A field can be used to explain the characteristics of an object or a class.

What are automatic properties?

What is automatic property? Automatic property in C# is a property that has backing field generated by compiler. It saves developers from writing primitive getters and setters that just return value of backing field or assign to it. Instead of writing property like this: public class Dummy.

What is the difference between properties and variables in C#?

In C# any "variable" that has a getter and setter is referred to as a property. A variable has no getters and setters or so that is what the text books say. My programming instructor made us have getters and setters for almost every variable that we created in Java.


2 Answers

Because they are implemented differently in the resulting IL code (and machine language). An Automatic property is still exposed as a public getter and setter, whereas a public field is just that - a single field..

Thus, implementing an auto property allows you at some later date to change the internal behavior of either the getter or setter (like adding a validator) without recompiling or re=coding any dependant classes that use it...

like image 52
Charles Bretana Avatar answered Oct 21 '22 06:10

Charles Bretana


Just to add to what other people have said, declaring a public field, the field is accessible for read and write. declaring public automatic property, although the property is public, you can still add modifier to control the accessibility at the get/set level.

public string FirstName { get; private set; }

The user of your class sees FirstName as public property. However, he/she cannot write to it.

like image 41
tranmq Avatar answered Oct 21 '22 07:10

tranmq