-->

22 December 2019

Asp.Net C# Property Examples (get, set)

  Asp.Net CS By Example       22 December 2019

  C# Property Examples (get, set):
      A Property is a method that used for gets or sets a value of variable or objects.
To make properties use the get and set keywords.

Property: We see a mobile. This mobile has a shape, a material,a volume.
It is a stylish mobile.It is have metal body.
It have front and back camera.It has 8 gb ram,
64 gb storage capasity.It has 6 inch display. etc.
With properties, we could model this mobile.It has metal body.It has 8 gb ram.


Syntax:
    int _number;
    public int Number
    {
        get { return _number; } 
        set {_number = value; } 
    }
        

Code: Program.cs

using System;

namespace ConsoleApplication1
{
   class Demo
    {
        int _number;
        public int Number
        {
            get
            {
                return _number;
            }
            set
            {
                _number = value;
            }
        }
    }

    class Program
    {
        static void Main()
        {
            Demo obj = new Demo();
            obj.Number = 2; // set { }
            Console.WriteLine(obj.Number); // get { }
        }
    }
}

Output:


Automatic:
The property also have a automatic property syntax. In this a hidden field is generated.
Then, the get and set statements are used the hidden field.
//C# program that uses automatically implemented property


Syntax:
   public int Number { get; set;}   
        

Code: Program.cs

using System;

namespace ConsoleApplication1
{
    class Demo
    {
        public int Number { get; set; }
    }

    class Program
    {
        static void Main()
        {
            Demo obj = new Demo();
            obj.Number = 2;
            obj.Number *= 2;
            Console.WriteLine(obj.Number);
        }
    }
}

Output:


logoblog

Thanks for reading Asp.Net C# Property Examples (get, set)

Previous
« Prev Post

No comments:

Post a Comment

Please do not enter any spam link in the comment box.