golden nugget online

Properties In C#

Properties in C#

Properties in C# is an important concept. Properties are the special member of a class. More precisely these are known as the accessors which means properties are used to access the private data of a class. With the help of properties we can access the private data more safely and in a convenient way. Properties contains two inbuilt methods "get" and "set". The combination of "get" and "set" is known as accessors. "Get accessor" is used to read the value and "set accessor" is used to write the value in properties.

Syntax:

<access modifier> <return type> <property name>
{
    get{}
    set{}
}

Based upon the "get" and "set" methods properties are of four types,

1. Both Read and Write

This type of property basically contains both "get" and "set" method to read and write value respectively.

2. Read Only

This property contains only the "get" method, which is used to get the value. 

3. Write Only

This property contains only the set method, which is used to set the value.

4. Short hand (auto implemented)

This property does not contain the logic part it's a short hand property and it gets implemented automatically.

Example of both read and write property,

using System;
class Employee {
    private string Empname;
    public string Display {
        set {
            Empname = value;
        }
        get {
            return Empname;
        }
    }
}
class Program {
    public static void Main(string[] args) {
        Employee obj = golden nugget online Employee();
        obj.Display = "uhtred";
        Console.WriteLine(obj.Display);
        Console.ReadLine();
    }
}

Example of Read Only,

using System;
class Employee {
    private string Empname = "Uhtred";
    public string Display {
        get {
            return Empname;
        }
    }
}
class Program {
    public static void Main(string[] args) {
        Employee obj = golden nugget online Employee();
        Console.WriteLine(obj.Display);
        Console.ReadLine();
    }
}

Example of Write Only,

class Employee {
    private string Empname;
    public string Display {
        set {
            Empname = value;
        }
    }
}
class Program {
    public static void Main(string[] args) {
        Employee obj = golden nugget online Employee();
        obj.Display = "Uhtred";
        Console.ReadLine();
    }
}

Example of Auto Implemented,

class Employee {
    public string Show {
        get;
        set;
    }
}
class Program {
    public static void Main(string[] args) {
        Employee obj = golden nugget online Employee();
        obj.Show = "Uhtred";
        Console.WriteLine(obj.Show);
        Console.ReadLine();
    }
}

Conclusion

Properties are a safe and easy way to get access to the private data of class. Depending upon the need we can use the type of property which we want in our project. "get" method will return value that we want to read and in "set" method we will set the value.