Wednesday, December 5, 2018
Home > C# > C# Get Set Functions

What is C# property?

Among the various features of Object-oriented programming languages. One which is very useful is information hiding. I.e. Only Allowing the access to specific data outside the class. We do this by defining the private members in the class. C# property get set is a functional mechanism that allows the user to read & write values of the members of a class. We usually define properties as public. They are special methods & we refer to them simply as accessors. Or C# get set accessors. In other languages, you might refer them as accessor and mutator or getter and setter as well.

C# get Set Accessors

We use C# get to read the value of a member of the class. It returns the value. Its return type should be same as of the data type for the member. A property which doesn’t have a get accessor is write-only. I.e. we can only use this variable to write only and we can’t read data from that variable.

And C# set to assign the value to the member of the class. A property without a set accessor is read-only. I.e. We can only read data from that particular variable.

Defining C# property get set

class test
{
    dataType variableName;
    public dataType variableName
    {
        get
        {
            return this._variableName;
        }
        set
        {
            this._ variableName = value;
        }
    }
}

The dataType can be any of the data types available in C#.

C# property Example

Example Program: –

namespace get_set
{
    public class Name
    {
        private string name;
        // C# get set accessors / C# Property get set
        public string NameProp
        {
            get
            {
                return name;
            }
            set
            {
                name = value;
            }
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Name n = new Name();
            n.NameProp = "Jhon"; //This will invoke set accessor
            System.Console.Write(n.NameProp + "\n"); 
            // This above statement invokes get Accessor
        }
    }
}

C# property

The above example just simply explains the concept of C# property get set. It has many uses such as you can validate data before making a change to the value of the member. Or we can perform all the basic operations available in C# here as well.

Let’s have a look at below given example to see how these work.

namespace get_set
{
    public class Number
    {
        private int no;
        // C# get set accessors / C# property
        public int NumbereProp
        {
            get
            {
                return no;
            }
            set
            {  
                /* Here we are confirming that if the value is a 
                     positive integer than it
                be assigned to no. Otherwise not.*/
                if(value > 0)
                {
                    no = value;
                }
            }
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Number n = new Number();
            n.NumbereProp = 10;
            System.Console.Write(n.NumbereProp + "\n\n\n");

            // Trying to assign a negative value to no.
            n.NumbereProp = -10;
            System.Console.Write(n.NumbereProp + "\n");
        }
    }
}

C# get set accessors


Here from the above image, it is clear that our property is not setting the negative value to no. Yet it keeps the previously assigned value.

We can also auto implement these functions. C# 3.0 and later provides this facility. As the name suggests auto implementation means that C# compiler auto implements these accessors. A below-given example shows how to use these auto-implemented accessors.

namespace get_set
{
    class CustomerClass
    {
        public double Purchases { get; set; }
        public int CustomerID { get; set; }
        public string CustomerName { get; set; }

        // Constructor of CustomerClass
        public CustomerClass(double purchases, int custid, string custname)
        {
            Purchases = purchases;
            CustomerID = custid;
            CustomerName = custname;          
        }
    }
    class Program
    {
        static void Main()
        {
            // Intialize a new object.
            CustomerClass customer = new CustomerClass(123.456,100 ,"Jan Doe");
            System.Console.Write("Customer Name = " + 
            customer.CustomerName+"\nCustomer Id =" + 
            customer.CustomerID + "\nTotal Bill = " + customer.Purchases);

            //Modify a property
            customer.Purchases += 499.99;
            System.Console.Write("\n\n\nCustomer Name = " + 
            customer.CustomerName + "\nCustomer Id =" + 
            customer.CustomerID + "\nTotal Bill = " + customer.Purchases);
        }
    }
}

C# property get set auto implemented

In this above example program, we didn’t provide any definition for accessors of the members of the class. And in the main function, we simply assigned and accessed those members.

As we already mentioned that we can have C# get set accessors for all the data types available in c#. This also includes user-defined data types as well. Such as Structures. Below is a program that shows how we use these accessor functions for structures in c#.

using System;

namespace get_set
{
     public struct StructExample
     {
          public int x;
          public string y;

          public StructExample(int a, string b)
          {
               this.x = a;
               this.y = b;
          }
     }

     class Program
     {
          private StructExample newStruct;
          
          public StructExample MyStruct
          {
               get { return newStruct; }
               set { newStruct = value; }
          }

          static void Main()
          {
               // Intialize a new object.
               StructExample newStruct = new StructExample(10, "Hello");

               //Accessing the values from structure
               System.Console.Write("Value of x = " + newStruct.x);
               System.Console.Write("\nValue of y = " + newStruct.y);
               //Setting new values  structure
               newStruct.x = 100;
               newStruct.y = "World";

               System.Console.Write("\nValue of x = " + newStruct.x);
               System.Console.Write("\nValue of y = " + newStruct.y+"\n");
          }
     }
}

C# get set for structure

 

 

 

 

This above program shows us how to use the C# property for user-defined data types such as structures. Like other data types, we can also put some checks while setting the value as well.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.