C# Properties

In C#, Properties enables class to provide a public way of setting and getting values or fields of the class. Properties provides Encapsulation in the class if we make all the fields of the class private and use only properties for getting and setting values. Prior to this, we were using method for this purpose. We can implement the logic also while setting values. Properties in C#, are read only or write only. They don’t have storage location. In C#, Properties are either read only or write only. They have accessors which are used to set and get values. Let's see an example where we are using Set and Get for getting and setting values.

using System;
public class Employee
{
            private int id;
            private string name;
            static int batch=2017;
            static string course="B. Tech.";
            public int ID
            {
            get
            {
                        return id;
            }
            set
            {
                        id=value;
            }
            }
            public string Name
            {
            get
            {
                        return name;
            }
            set
            {
                        name=value;
            }
            }
                        public static void Main (string[] args)
                        {
                                    Employee e=new Employee();
                                    e.ID=101;
                                    e.Name="Ayush Sharma";
                                    Console.WriteLine(e.ID+" "+e.Name);
                        }
}
Output
101 Ayush Sharma
C# properties Example: using logic while setting value                                        
using System;
public class Employee
{
            private int id;
            private string name;
            static int batch=2017;
            static string course="B. Tech.";
            public int ID
            {
            get
            {
                        return id;
            }
            set
            {
                        id=value;
            }
            }
            public string Name
            {
            get
            {
                        return name;
            }
            set
            {
                        Console.WriteLine("Enter Designation:");
                        string designation=Console.ReadLine();
                        name=value+" " +designation;                       
            }
            }
                        public static void Main (string[] args)
                        {
                                    Employee e=new Employee();
                                    e.ID=101;
                                    e.Name="Ayush Sharma";
                                    Console.WriteLine(e.ID+" "+e.Name);
                        }
}
Output
Enter Designation:
software developer
101 Ayush Sharma software developer