Properties in C#

Before talking about Property in C# I want to tell you about other mechanism that can also use 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 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 above problem we can use following solutions

1. Getter and Setter Methods- Programming languages that does 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(“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 of a class that provides a way to get/ set the value of a private field.

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 same program as we saw above but with the help of Properties. Auto Implemented Properties are also used in 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(“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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s