Field Vs Property

The normal variable what we declared so far is nothing but Field. Property is somewhat like a field with some differences. The key difference between field and property in C# is that a field is a variable of any type that is declared directly in the class while Property is a member that provides a flexible mechanism to read, write or compute the value of a private field.
Property itself will act like a method so a property cannot be decalred inside a method. We need to declare property directly inside class. Before accepting any value to property we can set certain conditions, only if all those conditions are met then we can assign that value to property. This is not possible in Field.

In the above syntax, we used keywords called get and set where get is the readable property and it returns a value, set is the writable property where we set conditions. If we want to make a property readonly we can simply remove set; from the property.

CODE

EG 1 . Creating MONTH property

class Program {
    static int month = 1;
    //Property can be elaborated and written as below
    static int Month{
        get {
            return month;
        }
        set {
            //value is the newly assigned value to property.
            if (value < 1 || value > 12) Console.WriteLine("Invalid Month");
            else month = value;
        }
    }

    static void Main(string[] args) {
        Month = 32;
        Console.WriteLine(Month);
        Console.WriteLine();
        Month = 5;
        Console.WriteLine(Month);
    }
}


(Click Here, For more exercises)