Click here to Skip to main content
15,896,557 members
Articles / Programming Languages / C#

Properties in C#

Rate me:
Please Sign up or sign in to vote.
3.91/5 (12 votes)
11 Sep 2014CPOL2 min read 30K   12   8
Properties in C#

Before talking about Property in C#, I want to tell you about other mechanisms that can also be used in place of properties.

Make the Class Field Public

Making the class fields public and exposing to the external world is bad, as you will not have control over what gets assigned and returned. We can understand this with the help of the following program.

C#
using System;
public class Student
{
public int ID;
public string Name;
public int PassMark = 35;
}
public class Program
{
public static void Main(string[] args)
{
Student s = new Student();
s.ID = -101;
s.Name = null;
s.PassMark = 0;
Console.WriteLine("ID = {0} \nName = {1} \nPassing Marks = {2}", s.ID, s.Name, s.PassMark);
Console.ReadLine();
}
}

Problems with public fields:

  1. ID should always be non-negative number
  2. Name cannot be set to NULL
  3. If Student Name is missing “No Name” should be returned
  4. PassMark should be read only

To solve the above problem, we can use the following solutions:

1. Getter and Setter Methods

Programming languages that do not have properties use getter and setter methods to encapsulate the protect fields.

C#
using System;
public class Student
{
////First Program start
//public int ID;
//public string Name;
//public int PassMark = 35;
////First Program end
//getter setter method use start
private int _ID;
private string _Name;
private int _PassMark = 35;
public void SetId(int Id)
{
if (Id <= 0)
{
throw new Exception("Student Id cannot be negative");
}
this._ID = Id;
}
public int GetId()
{
return this._ID;
}
public void SetName(string Name)
{
if (string.IsNullOrEmpty(Name))
{
throw new Exception("Student Name cannot be NULL or Empty");
}
this._Name = Name;
}
public string GetName()
{
return string.IsNullOrEmpty(this._Name) ? "No Name" : this._Name;
}
public int GetPassMark()
{
return this._PassMark;
}
//getter setter method use end
}
public class Program
{
public static void Main(string[] args)
{
Student s = new Student();
////First Program start
//s.ID = -101;
//s.Name = null;
//s.PassMark = 0;
////First Program end
//getter setter method use start
s.SetId(101);
s.SetName("Akash");
//getter setter method use end
////First Program start
//Console.WriteLine("ID = {0} \nName = {1} \nPassing Marks = {2}", s.ID, s.Name, s.PassMark);
////First Program end
//getter setter method use start
Console.WriteLine("ID = {0} \nName = {1} \nMarks= {2}", s.GetId(),s.GetName(),s.GetPassMark());
//getter setter method use end
Console.ReadLine();
}
}

Note: In the above code, we created PassMark field as read only by not creating a SetPassMark() method.

2. Using Properties

A property is a member that provides a flexible mechanism to read, write, or compute the value of a private field. Properties can be used as if they are public data members, but they are actually special methods called accessors. This enables data to be accessed easily and still helps promote the safety and flexibility of methods.

Property can be following types:

  1. Read/Write Properties
  2. Read Only Properties
  3. Write Only Properties
  4. Auto Implemented Properties

In C# to encapsulate and protect fields, we use properties. We use get and set accessors to implement properties.

  1. Read/Write Properties: A property with both getand set accessor is a Read/Write property.
  2. Read Only Properties: A property with only get accessor is a Read only property.
  3. Write Only Properties: A property with only set accessor is a Write only property.
  4. Auto Implemented Properties: If there is no additional logic in the property accessors, then we can make use of auto- implemented properties introduced in C# 3.0.

Auto implemented properties reduce the amount of code that we have to write.

When we use auto-implemented properties, the compiler creates a private, anonymous field that can only be accessed through the property’s get and set accessors.

We can understand Properties in C# with the help of the same program as we saw above but with the help of Properties. Auto Implemented Properties are also used in the following program:

C#
using System;
public class Student
{
////First Program start
//public int ID;
//public string Name;
//public int PassMark = 35;
////First Program end
////getter setter method use start
//private int _ID;
//private string _Name;
//private int _PassMark = 35;
//public void SetId(int Id)
//{
//   if (Id <= 0)
//   {
//       throw new Exception("Student Id cannot be negative");
//   }
//   this._ID = Id;
//}
//public int GetId()
//{
//   return this._ID;
//}
//public void SetName(string Name)
//{
//   if (string.IsNullOrEmpty(Name))
//   {
//       throw new Exception("Student Name cannot be NULL or Empty");
//   }
//   this._Name = Name;
//}
//public string GetName()
//{
//   return string.IsNullOrEmpty(this._Name) ? "No Name" : this._Name;
//}
//public int GetPassMark()
//{
//   return this._PassMark;
//}
////getter setter method use end
//properties use start
private int _ID;
private string _Name;
private int _PassMark = 35;
//Read/Write Property
public int Id
{
set
{
if (value <= 0)
{
throw new Exception("Student Id cannot be negative");
}
this._ID = value;
}
get { return this._ID; }
}
//Read/Write Property
public string Name
{
set
{
if (string.IsNullOrEmpty(value))
{
throw new Exception("Student Name cannot be NULL or Empty");
}
this._Name = value;
}
get {return string.IsNullOrEmpty(this._Name) ? "No Name" : this._Name; }
}
//ReadOnly Property
public int PassMark
{
get { return this._PassMark; }
}
//properties use end
//Auto Implemented Property use start
public string Email { get; set; }
public string City { get; set; }
//Auto Implemented Property use end
}
public class Program
{
public static void Main(string[] args)
{
Student s = new Student();
////First Program start
//s.ID = -101;
//s.Name = null;
//s.PassMark = 0;
////First Program end
//getter setter method use start
//s.SetId(101);
//s.SetName("Akash");
//getter setter method use end
//properties use start
s.Id = 101;
s.Name = "Akash";
//properties use end
//Auto Implemented Property use start
s.City = "Pune";
s.Email = "akash.jain@mail.com";
//Auto Implemented Property use end
////First Program start
//Console.WriteLine("ID = {0} \nName = {1} \nPassing Marks = {2}", s.ID, s.Name, s.PassMark);
////First Program end
////getter setter method use start
//Console.WriteLine("ID = {0} \nName = {1} \nMarks= {2}", s.GetId(),s.GetName(),s.GetPassMark());
////getter setter method use end
//properties use start
Console.WriteLine("ID = {0} \nName = {1} \nMarks= {2}", s.Id, s.Name, s.PassMark);
//properties use end
//Auto Implemented Property use start
Console.WriteLine("City = {0} \nEMail= {1}", s.City, s.Email);
//Auto Implemented Property use end
Console.ReadLine();
}
}

Note: The advantage of properties over traditional Get() and Set() methods is that we can access them as if they were public fields.

value keyword (used in public int Id property) - The contextual keyword value is used in the set accessor in ordinary property declarations. It is similar to an input parameter on a method. The word value references the value that client code is attempting to assign to the property. In the above example, class Student has a property called Id that uses the value parameter to assign a new number to the backing field _ID.

This article was originally posted at http://dotnetpad.wordpress.com/2014/06/25/properties-in-c

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
India India
I am "Akash Jain" working in IT Industry from last 6 years. From the beginning of my career I worked with C# for both windows and web application. In my short career I worked for 2 Major ERP Applications, e-commerce applications, CMS based applications and also few static websites.

I am a MCP for web application for ASP.NET 4.0. I have also done PMP training as project management is one of my interest area.

Comments and Discussions

 
QuestionYour example code Pin
KP Lee14-Sep-14 9:21
KP Lee14-Sep-14 9:21 
QuestionAgree with s2bert Pin
KP Lee14-Sep-14 8:06
KP Lee14-Sep-14 8:06 
GeneralMy vote of 3 Pin
Kishor Deshpande13-Sep-14 3:54
professionalKishor Deshpande13-Sep-14 3:54 
GeneralMy vote of 2 Pin
s2bert12-Sep-14 2:53
s2bert12-Sep-14 2:53 
Dealing with such a fundamental topic demands delivery of a great deal of depth, structure and relevant example. Not doing so leaves people at best no better off, or worse, more confused then they were before.

I suggest taking some time to better organise and group the information into a comprehensive set of specific points, perhaps such things as the use of properties in specific implementations of patterns, where you can introduce interfaces and abstract classes making good or bad use of properties or fields.

It's a pity because I do like good articles on the fundamentals and I think you picked an oft overlooked topic so, cudos for that.
GeneralMy vote of 2 Pin
Erlend Robaye12-Sep-14 2:04
Erlend Robaye12-Sep-14 2:04 
GeneralMy vote of 2 Pin
LostTheMarbles12-Sep-14 1:04
professionalLostTheMarbles12-Sep-14 1:04 
GeneralMy vot eof 4 Pin
Klaus Luedenscheidt11-Sep-14 19:24
Klaus Luedenscheidt11-Sep-14 19:24 
GeneralRe: My vot eof 4 Pin
John Brett12-Sep-14 2:58
John Brett12-Sep-14 2:58 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.