C Sharp Properties

C# Properties

Without any storage location, the C# Properties are accessed like fields and are an extension of fields. It can be read-only or write-only. To set, get or compute the values of the properties, they have accessors and while setting the values, the users can have logic. The fields can’t be accessed from outside the class directly when the fields of the class are private. Thus the C# properties are used for setting or getting values in this case.

Example 1:

using System;  
   public class Student  
    {  
        private int age;  
 
        public int std  
        {  
            get  
            {  
                return age;  
            }  
            set  
            {  
                age = value;  
            }  
        }  
   }  
   class Details{  
       public static void Main(string[] args)  
        {  
            Student s1 = new Student();  
            s1.std = 10;  
            Console.WriteLine("Student Age: " + s1.std);  
 
        }  
    }

Output:

Explanation:

In the above example, we are displaying a simple example of C# properties. Here, the age of the student is displayed on the output screen.

Example 2:

using System;  
   public class Student  
    {  
        private int age;  
 
        public int std  
        {  
            get  
            {  
                return age;  
            }  
            set  
            {  
                age = value + 2;  
            }  
        }  
   }  
   class Details{  
       public static void Main(string[] args)  
        {  
            Student s1 = new Student();  
            s1.std = 10;  
            Console.WriteLine("Student Age: " + s1.std);  
 
        }  
    }

Output:

Explanation:

In the above example, we are displaying the use of having logic while setting value. Here, the age of the student plus 2 years is displayed on the output screen.

Example 3:

using System;  
   public class Student  
    {  
        private static int n;  
 
        public Student()  
        {  
            n++;  
        }  
        public static int Num  
        {  
            get  
            {  
                return n;  
            }  
         }   
   }  
   class Details{  
       public static void Main(string[] args)  
        {  
            Student s1 = new Student();  
            Student s2 = new Student();  
            Student s3 = new Student();  
 
            Console.WriteLine("No. of Students: " + Student.Num);  
 
        }  
    }

Output:

Explanation:

In the above example, we are displaying the use of the read-only property. Here, the count or the number of the students is returned and is displayed on the output screen.