Deane
Deane

Reputation: 8737

When should you use a field rather than a property?

Can anyone clearly articulate when you use a field and when to use a property in class design?

Consider:

public string Name;

Or:

private string _Name;
public string Name
{
   get { return _Name; }
   set { _Name = value; }
}

I realize that the second method is more proper and flexible, so that's what I try to use, generally.

But then why do I see people use the first method? Are they just lazy, or is there some specific situation where it's the correct choice? Is it just a matter of preference?

Upvotes: 12

Views: 3845

Answers (8)

kaz
kaz

Reputation: 11

From a different perspective, I like Properties.

That is because the reference count of Property is shown by enabling CodeLens as default in MS Visual Studio (2022 version 17.10.5 as of today), but the count of Field is not.

Upvotes: 1

sotrh
sotrh

Reputation: 406

A property like defined above acts like a getter and setter. The only benefits of using a property is that you can treat it like a variable with access restriction.

public string Name { get; private set; }

This property can be accessed publicly, but can only be set privately. (You wouldn't want anyone changing your name with out your consent now would you! ;) )

Upvotes: 0

Alan
Alan

Reputation: 46813

Well in C# 3.0 you can actually write:

public string Name {get; set;}

Which allows you to be proper and lazy.

Generally speaking, with properties, you get proper encapsulation. You have the choice to allow setting a value, or getting it, or both. Using a public member, you don't have that option.

It's probably one-part preference, and one-part how your team decides to handle quick and dirty class definitions, but I would say, use properties for get/sets.

To answer

Can anyone clearly articulate when you use an attribute and when to use a property in class design?

You shouldn't ever use a public attribute. You should always use a property instead. It's safer and more flexible. That said, people will be lazy, and just use a public member. However, with C# 3.0 you can use a more terse syntax to define properties, which should satisfy your inner laziness.

Simply type prop and hit <tab> to expedite the laziness in adding a property.

Upvotes: 15

AakashM
AakashM

Reputation: 63340

In addition to the already-given reasons for preferring properties, there's also lots of cool stuff in System.ComponentModel to do with data binding and change notification that only works with properties, rather than fields. For example, look at the documentation around PropertyChangedHandler.

Upvotes: 1

tranmq
tranmq

Reputation: 15658

When you make the field public, you allow the user to do whatever they want to do to the field. They can assign unexpected values, invalid values, values that can cause overflow, etc.

With the property, you have control over whether to allow the setting of new values to the field, massaging the value before storing it, notifying interested parties about the change of the field's value, etc. And the same idea for returning value through the getter. For .NET framework from 2.0 up, you can set the accessor for the getter, setter. Say, you only want the user to only have read access to the field, then you make the getter public, but the setter private or protected.

Upvotes: 0

abatishchev
abatishchev

Reputation: 100248

Using properties you can control it's security:

public string Foo { protected get; private set; }

Properties gives easy way to raise events:

public string Foo
{
  get { return _foo; }
}
set
{
  bool cancel = false;
  if(BeforeEvent != null) // EventHandler<CancelEventArgs> BeforeEvent
  {
    CancelEventArgs e = new CancelEventArgs();
    BeforeEvent(this, e);
    cancel = e.Cancel;
  }
  if(!cancel)
  {
    _foo = value;
    if(AfterEvent != null) // EventHandler<EventArgs> AfterEvent
    {
      AfterEvent(this, new EventArgs());
    }
  }
}

Also I often use code like this:

string Foo
{
  set
  {
    IsFooSet = value != null;
  }
}

bool IsFooSet
{
  get { return _isFoo; }
  set
  { 
   _isFoo = value;
   if(value) // some event raise or controls on form change
  }
}

Upvotes: 0

Billy
Billy

Reputation: 15706

Just some additional information to Alan's reply:

public string Name {get; set;}

is the same as

private string _Name;

public string Name{   
get { return _Name; }   
set { _Name = value; }
}

If you want to disallow the set function of Name, you can have

public string Name {get; private set;}

Upvotes: 14

Christian C. Salvad&#243;
Christian C. Salvad&#243;

Reputation: 827256

Properties are more maintainable than fields, you can encapsulate logic in your setters/getters, allowing you to hide the implementation.

They also make refactoring easier.

More information:

Upvotes: 4

Related Questions