Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Properties in C#

0.00/5 (No votes)
11 Sep 2014 1  
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.

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.

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(&ldquo;Student Id cannot be negative&rdquo;);
}
this._ID = Id;
}
public int GetId()
{
return this._ID;
}
public void SetName(string Name)
{
if (string.IsNullOrEmpty(Name))
{
throw new Exception(&ldquo;Student Name cannot be NULL or Empty&rdquo;);
}
this._Name = Name;
}
public string GetName()
{
return string.IsNullOrEmpty(this._Name) ? &ldquo;No Name&rdquo; : 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(&ldquo;Akash&rdquo;);
//getter setter method use end
////First Program start
//Console.WriteLine(&ldquo;ID = {0} \nName = {1} \nPassing Marks = {2}&rdquo;, s.ID, s.Name, s.PassMark);
////First Program end
//getter setter method use start
Console.WriteLine(&ldquo;ID = {0} \nName = {1} \nMarks= {2}&rdquo;, 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:

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(&ldquo;Student Id cannot be negative&rdquo;);
//   }
//   this._ID = Id;
//}
//public int GetId()
//{
//   return this._ID;
//}
//public void SetName(string Name)
//{
//   if (string.IsNullOrEmpty(Name))
//   {
//       throw new Exception(&ldquo;Student Name cannot be NULL or Empty&rdquo;);
//   }
//   this._Name = Name;
//}
//public string GetName()
//{
//   return string.IsNullOrEmpty(this._Name) ? &ldquo;No Name&rdquo; : 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(&ldquo;Student Id cannot be negative&rdquo;);
}
this._ID = value;
}
get { return this._ID; }
}
//Read/Write Property
public string Name
{
set
{
if (string.IsNullOrEmpty(value))
{
throw new Exception(&ldquo;Student Name cannot be NULL or Empty&rdquo;);
}
this._Name = value;
}
get {return string.IsNullOrEmpty(this._Name) ? &ldquo;No Name&rdquo; : 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(&ldquo;Akash&rdquo;);
//getter setter method use end
//properties use start
s.Id = 101;
s.Name = &ldquo;Akash&rdquo;;
//properties use end
//Auto Implemented Property use start
s.City = &ldquo;Pune&rdquo;;
s.Email = &ldquo;akash.jain@mail.com&rdquo;;
//Auto Implemented Property use end
////First Program start
//Console.WriteLine(&ldquo;ID = {0} \nName = {1} \nPassing Marks = {2}&rdquo;, s.ID, s.Name, s.PassMark);
////First Program end
////getter setter method use start
//Console.WriteLine(&ldquo;ID = {0} \nName = {1} \nMarks= {2}&rdquo;, s.GetId(),s.GetName(),s.GetPassMark());
////getter setter method use end
//properties use start
Console.WriteLine(&ldquo;ID = {0} \nName = {1} \nMarks= {2}&rdquo;, s.Id, s.Name, s.PassMark);
//properties use end
//Auto Implemented Property use start
Console.WriteLine(&ldquo;City = {0} \nEMail= {1}&rdquo;, 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.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here