Friday 27 May 2016

class properties

class properties

C# 3.0 introduce with auto initialize properties with getter and setter method. It is very useful to validate value before assigning.

What is Auto property initialize?
A variable is a type that stores some value. And the property member of a class provides access to variable.
A field member can be accessed directly but a property member is always accessed through accessor and modifier methods called get and set respectively.

Syntax:

public int Id { get; set; }
public string Name { get; set; }

The following are the types of properties:
  • Read only property.
  • Write only property.
  • Auto implemented property.

Read only property by just defining the get accessor in the property implementation.
Read only property has only get accessor.
Example:

using System;

class Program
{
   
    static void Main()
    {
        myClass cls = new myClass();

        Console.WriteLine(cls._name);
    }
}

class myClass
{
    protected string Name = "Sample";
   
    public string _name
    {
        get
        {
            return Name;
        }
    }

}
Using get accessor you can read protected variable. You can not assign value to that with set modifier. Let’s understand about set modifier.
Write only property by just defining the set access modifier in the property implementation.
Write only property has only set accessor.
Example:

using System;

class Program
{
   
    static void Main()
    {
        myClass cls = new myClass();
        cls._name = "Sample";
        cls.Print();
    }
}

class myClass
{
    protected string Name = "Sample";
   
    public string _name
    {
        set
        {
            Name = value;
        }
    }

    public void Print()
    {
        Console.WriteLine(this.Name);
    }

}

Auto implemented property introduce C# 3.0. It is a new class property called auto implemented property that created without get and set accessor implementation.
You can define get and set only no implementation inside get and set;
Example:

using System;

class Program
{
   
    static void Main()
    {
        myClass cls = new myClass();
        cls.Name = "Sample";
        cls.Print();
    }
}

class myClass
{
    public string Name { get; set; }

    public void Print()
    {
        Console.WriteLine(this.Name);
    }

}

you can also visit:  www.mybook-lang.com

No comments:

Post a Comment