OOP Properties in C#


Properties
Properties provide a flexible mechanism to read, write, validate or compute a private field. You can also use public fields in properties, but if we use a public field in a property then anybody can access our field in a program. A property makes our field secure, and we can change our rule (property) in one location, and it is easy to use anywhere.
Look at the following example.
// File Name:- Program.cs

    class Program

    {

        // Private fields

        private int Emp_Id;

        private string Emp_Name = string.Empty;

       

        //ID Property Declaration

        public int ID

        {

            //Get is use for Reading field

            get

            {

                return Emp_Id;

            }

            //Set is use for writing field

            set

            {

                Emp_Id = value;

            }

        }

        //Name Property Declaration

        public string Name

        {

            //Get is use for Reading field

            get

            {

                return Emp_Name;

            }

            //Set is use for writing field

            set

            {

                Emp_Name = value;

            }

        }

        static void Main(string[] args)

        {

            //Create an object of Program class.

            Program Prg = new Program();

            Prg.ID = 7;

            Prg.Name = "Sourabh Mishra";

            Console.WriteLine("Employee Id:={0}", Prg.ID);

            Console.WriteLine("Employee Name:={0}", Prg.Name);

            Console.ReadLine();

        }

    }
 
In the preceding example, we have the following two private fields:

  1. Emp_Id (int) 
  2. Emp_name (string)

And we have two properties, Id and Name. When a property is created we have the two methods Get and Set. Get is for reading the value and Set is for writing the value fo a field. When we just want to create a read-only property, we only use Get.

// Private fields

        private int Emp_Id;

        //ID Property Declaration

        public int ID

        {

            //Get is use for Reading field

            get

            {

                return Emp_Id;

            }

            //Set is use for writing field

            set

            {

                Emp_Id = value;

            }

        }
Here in the Get method note that I just return the Emp_Id field. In the Set method I declare the value in Emp_Id. I know you think, what is this keyword "value". The value keyword is always used in the set method, for writing data into a field.
Look at the example and then you can easily understand this value keyword.
// File Name:- Program.cs

    class Program

    {

        // Private fields

        private int Emp_Id;

        private string Emp_Name = string.Empty;

       

        //ID Property Declaration

        public int ID

        {

            //Get is use for Reading field

            get

            {

                return Emp_Id;

            }

//Set is use for writing field

            set

            {

                //Here validaion is user should enter more then 0

                if (value > 0)

                {

                    Emp_Id = value;

                }

            }

        }

        //Name Property Declaration

        public string Name

        {

            //Get is use for Reading field

            get

            {

                return Emp_Name;

            }

            //Set is use for writing field

            set

            {

                Emp_Name = value;

            }

        }

        static void Main(string[] args)

        {

            //Create an object of Program class.

            Program Prg = new Program();

            Prg.ID = 2;

            Prg.Name = "Sourabh Mishra";

            Console.WriteLine("Employee Id:={0}", Prg.ID);

            Console.WriteLine("Employee Name:={0}", Prg.Name);

            Console.ReadLine();

        }

    }
If your value is smaller than 0 in the Id field then you get the value 0 in the Id property. So here if you look at the code above:
//Set is use for writing field

   set

   {

      //Here validaion is user shoul enter more then 0

        if (value > 0)

        {

           Emp_Id = value;

         }
    }

 
Auto Implemented Properties

In the preceding examples, you learned how to implement properties. Perhaps you don't want to implement them without logic, for example in Example 2 we validate the value. If you just want to simply implement your property then Auto implementation is the best feature of C# 3.0.
// Example 3- FileName:- Program.cs

    class Program

    {

        //ID Property without any implementation

        public int ID

        {

            get;

            set;

        }

        //Name Property without any implementation

        public string Name

        {

            get;

            set;

        }

        static void Main(string[] args)

        {

            Program prg = new Program();

            //Set Value in ID Property

            prg.ID = 2;

            //Set Value in Name Property

            prg.Name = "Sourabh Mishra";

            Console.WriteLine("Id:-{0}", prg.ID);

            Console.WriteLine("Name:-{0}", prg.Name);

            Console.ReadKey();

        }

    }
Look at the above example. There are no implementations in the get and set methods. And also you don't need to create private fields. So Auto implemented properties are helpful, when you don't think you need any validation, comptation or any implementation.
Real Life Example on Properties
I know many beginner programmers always think, how to use this in a web application or Windows application, here is the example. Look at the following example.
//File Name:- WebForm1.aspx

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

    <title>Untitled Page</title>

</head>

<body>

    <form id="form1" runat="server">

    <table>

    <tr>

    <td>

    <asp:Label ID ="lblId" Text ="Id" runat="server" ></asp:Label>

    </td>

    <td>

    <asp:TextBox ID ="txtId" runat ="server" ></asp:TextBox>

    </td>

    </tr>

    <tr>

    <td>

    <asp:Label ID ="lblName" Text ="Name" runat="server" ></asp:Label>

    </td>

    <td>

    <asp:TextBox ID ="txtName" runat ="server" ></asp:TextBox>

    </td>

    </tr>

    <tr>

    <td>

    <asp:Button ID ="BttnSubmit" runat ="server" Text ="Submit"

            onclick="BttnSubmit_Click" />

    </td>

    </tr>

   

    </table>

    </form>

</body>

</html>
 
//File Name:- PropertiesExample.cs
 

    public class StudentInfo

    {

        private int _Id;

        private string  _Name=string .Empty ;

        public int Id

        {

            get

            {

                return _Id;

            }

            set

            {

                _Id = value;

            }

        }

        public string Name

        {

            get

            {

                return _Name;

            }

            set

            {

                _Name = value;

            }

        }

    }

//File Name:- WebForm1.aspx.cs

        protected void BttnSubmit_Click(object sender, EventArgs e)

        {

            //Create Object of StudentInfo.

            StudentInfo _objStudentInfo = new StudentInfo();

           

            //Set Value of Id property through textbox value

            _objStudentInfo.Id =int .Parse(txtId.Text);

           

            //Set Value of Name property through textbox value

            _objStudentInfo.Name = txtName.Text;

           

            //Get value of Id.

            Response.Write("Student Id:-"+_objStudentInfo .Id );

            Response.Write("<br/>");

            //Get value of Name.

            Response.Write("Student Name:-" + _objStudentInfo.Name );

        }
Look at the preceding example. In this example I create a class (StudentInfo). Here we have 2 properties, Id and Menu. After that we call these two properties.

Static Properties
A static property is similar to a static method. It uses the composite name to be accessed. Static properties use the same get and set tokens as instance properties. They are useful for abstracting global data in programs.

static class Settings
{
    public static int DayNumber
    {
  get
                       {
                    return DateTime.Today.Day;
                      }
       }

    public static string DayName
    {
    get
    {
    return DateTime.Today.DayOfWeek.ToString();
    }
   }

    public static bool Finished
    {
    get;
    set;
    }
}

class Program
{
    static void Main()
    {
//
// Read the static properties.
//

Console.WriteLine(Settings.DayNumber);
Console.WriteLine(Settings.DayName);
//
// Change the value of the static bool property.
//

Settings.Finished = true;
Console.WriteLine(Settings.Finished);
 }
}


FAQ on Properties
Q.1: Can I use only private access spcifiers for defining fields in properties?
Ans.: No, you can use all access specifiers (public, private and protected) for defining a feld. The benefit of defining a private field is that your field is protected, nobody can access it directly.
Q.2: What is the diffrence between Properties and Variables?
Ans.: When you define a varriable as private you can't acess it in other asssamblies. If you declare a varriable as public, everybody can access your varriable, it's not safe. So in properties you define a field as private and use it in the public properties.


Similar Articles