Why We Need Properties in C#

Why we need Properties in C#

Think about it: You have a room for which you want to regulate who can come in to keep the internal consistency and security of that room as you would not want anyone to come in and mess it up and leave it like nothing happened. So that room would be your instantiated class and properties would be the doors people come use to get into the room. You make proper checks in the setters and getters of your properties to make sure any unexpected things come in and leave.

More technical answer would be encapsulation and you can check this answer to get more information on that: https://stackoverflow.com/a/1523556/44852

class Room {
public string sectionOne;
public string sectionTwo;
}

Room r = new Room();
r.sectionOne = "enter";

People is getting in to sectionOne pretty easily, there wasn't any checking.

class Room 
{
private string sectionOne;
private string sectionTwo;

public string SectionOne
{
get
{
return sectionOne;
}
set
{
sectionOne = Check(value);
}
}
}

Room r = new Room();
r.SectionOne = "enter";

now you checked the person and know about whether he has something evil with him.

Why do we need Fields if there are Properties?

Although automatic properties blur the distinction quite a bit, there is a fundamental difference between a field and a property:

  • A field is a data member capable of storing things,
  • A property is a method or a pair of methods which, through help of the compiler, can be used as if they were a field.

In other words, when you write

public float musicBPM { get; set; } 

the compiler creates something like this:

private float musicBPM_property;
public float musicBPM {
get { return musicBPM_property; }
set { musicBPM_property = value; }
}

When you make an automatic property, the field is still there, but the compiler cleverly hides it from you.

That is why the fields are going to remain as a concept in .NET. However, automatic read-only properties of C# 6 make it possible to eliminate fields from the code that you write manually.

What is the difference between a field and a property?

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.

public class MyClass
{
// this is a field. It is private to your class and stores the actual data.
private string _myField;

// this is a property. When accessed it uses the underlying field,
// but only exposes the contract, which will not be affected by the underlying field
public string MyProperty
{
get
{
return _myField;
}
set
{
_myField = value;
}
}

// This is an AutoProperty (C# 3.0 and higher) - which is a shorthand syntax
// used to generate a private field for you
public int AnotherProperty { get; set; }
}

@Kent points out that Properties are not required to encapsulate fields, they could do a calculation on other fields, or serve other purposes.

@GSS points out that you can also do other logic, such as validation, when a property is accessed, another useful feature.

Why prefer Properties to public variables?

We've had this subject before but I can't find anything now.

In brief: your needs might change: where there's no sanity check now, one might be required in the future. However, if you change your public fields to properties, this breaks binary compatiblity: every client who uses your code/library would have to re-compile.

This is bad because it potentially costs a lot of money.

Using properties from the beginning avoids this problem. This even counts for code that is not part of a library. Why? Because you never know: the code (even if highly domain-specific!) might prove useful so you want to refactor it to a library. This refactoring process is obviously made much easier if you are already using properties in place of public/protected fields.

Additionally, writing public properties is easy in C# 3.0 because you can just use the auto-implemented properties, saving you quite a bit of code:

public DataType MyProperty { get; set; }

Will implement the necessary backing field and getter/setter code for you.

I will add a personal note: .NET's behaviour in this regard is somewhat lazy. The compiler could just change public fields to properties on the fly, thus avoiding the problem. VB6 already did this for COM-exposed classes and I see absolutely no reason for VB.NET and C# not to do the same. Perhaps someone on the compiler teams (Jared?) could comment on this.

Why do we use fields & properties instead of just a variable?

Just for encapsulation principle. For hinding concrete implementaiton, and plus, you have an opportunity (in this case) to add additional code inside get/set.

If you don't need addittional code, you can use just

public string Name{get;set;}

or use fileds, as you would like. But using properties is a guideline offered by Microsoft.

So basically all, follow it.

What is the purpose of the get and set properties in C#

They are just accessors and mutators. That's how properties are implemented in C#

In C# 3 you can use auto-implemented properties like this:

public int MyProperty { get; set; }

This code is automatically translated by the compiler to code similar to the one you posted, with this code is easier to declare properties and they are ideal if you don't want to implement custom logic inside the set or get methods, you can even use a different accessor for the set method making the property immutable

public int MyProperty { get; private set; }

In the previous sample the MyProperty will be read only outside the class where it was declared, the only way to mutate it is by exposing a method to do it or just through the constructor of the class. This is useful when you want to control and make explicit the state change of your entity

When you want to add some logic to the properties then you need to write the properties manually implementing the get and set methods just like you posted:

Example implementing custom logic

private int myProperty;
public int MyProperty
{
get
{
return this.myProperty;
}
set
{
if(this.myProperty <=5)
throw new ArgumentOutOfRangeException("bad user");
this.myProperty = value;
}
}

When to use properties instead of functions

I tend to use properties if the following are true:

  • The property will return a single, logic value
  • Little or no logic is involved (typically just return a value, or do a small check/return value)

I tend to use methods if the following are true:

  • There is going to be significant work involved in returning the value - ie: it'll get fetched from a DB, or something that may take "time"
  • There is quite a bit of logic involved, either in getting or setting the value

In addition, I'd recommend looking at Microsoft's Design Guidelines for Property Usage. They suggest:

Use a property when the member is a logical data member.

Use a method when:

  • The operation is a conversion, such as Object.ToString.
  • The operation is expensive enough that you want to communicate to the user that they should consider caching the result.
  • Obtaining a property value using the get accessor would have an observable side effect.
  • Calling the member twice in succession produces different results.
  • The order of execution is important. Note that a type's properties should be able to be set and retrieved in any order.
  • The member is static but returns a value that can be changed.
  • The member returns an array. Properties that return arrays can be very misleading. Usually it is necessary to return a copy of the internal array so that the user cannot change internal state. This, coupled with the fact that a user can easily assume it is an indexed property, leads to inefficient code. In the following code example, each call to the Methods property creates a copy of the array. As a result, 2n+1 copies of the array will be created in the following loop.

Why use simple properties instead of fields in C#?

Using properties has a couple of distinct advantages:

  • It allows for versioning if later you need extra logic. Adding logic to the getter or setter won't break existing code.
  • It allows data binding to work properly (most data binding frameworks don't work with fields).

In addition, there are almost no disadvantages. Simple, automatic properties like this get inlined by the JIT compiler, so there is no reason not to use them.

Also, you mentioned:

Other than these fairly rare cases, changing Foo to be a computed property later results in 0 lines of code changed.

This doesn't require your code to be changed, but it does force you to recompile all of your code. Changing from a field to a property is a breaking API change which will require any assembly which references your assembly to be recompiled. By making it an automatic property, you can just ship a new binary, and maintain API compatibility. This is the "versioning" advantage I mentioned above...

Properties vs. Fields: Need help grasping the uses of Properties over Fields

You should not worry about the extra code needed for accessing fields via properties, it will be "optimized" away by the JIT compiler (by inlining the code). Except when it is too large to be inlined, but then you needed the extra code anyway.

And the extra code for defining simple properties is also minimal:

public int MyProp { get; set; } // use auto generated field.

When you need to customize you can alway define your own field later.

So you are left with the extra layer of encapsulation / data protection, and that is a good thing.

My rule: expose fields always through properties

What are Automatic Properties in C# and what is their purpose?

Automatic Properties are used when no additional logic is required in the property accessors.

The declaration would look something like this:

public int SomeProperty { get; set; }

They are just syntactic sugar so you won't need to write the following more lengthy code:

 private int _someField;
public int SomeProperty
{
get { return _someField;}
set { _someField = value;}
}


Related Topics



Leave a reply



Submit