C# Properites doesn't have storage location. C# Properites are extension of fields and accessed like fields.
The Properties have accessors that are used to set, get or compute their values.
using System; public class Employee { private string name; public string Name { get { return name; } set { name = value; } } } class TestEmployee{ public static void Main(string[] args) { Employee e1 = new Employee(); e1.Name = "Sonoo Jaiswal"; Console.WriteLine("Employee Name: " + e1.Name); } }
Output:
using System; public class Employee { private string name; public string Name { get { return name; } set { name = value+" rookienerd"; } } } class TestEmployee{ public static void Main(string[] args) { Employee e1 = new Employee(); e1.Name = "Sonoo"; Console.WriteLine("Employee Name: " + e1.Name); } }
Output:
using System; public class Employee { private static int counter; public Employee() { counter++; } public static int Counter { get { return counter; } } } class TestEmployee{ public static void Main(string[] args) { Employee e1 = new Employee(); Employee e2 = new Employee(); Employee e3 = new Employee(); //e1.Counter = 10;//Compile Time Error: Can't set value Console.WriteLine("No. of Employees: " + Employee.Counter); } }
Output: