We are providing online training of realtime Live project on Asp.Net MVC with Angular and Web API. For more information click here. If you have any query then drop the messase in CONTACT FORM

Sunday, July 5, 2015

Properties Indexers

Properties
  • It is an option provided in Object-Oriented Language to provide access to any value of a class outside of the class.
  • If a class contains any values in it that should be accessible outside of the class access to the value can be given in two different ways.
  • Store the value in a 'public' variable. So that it can be accessed by anyone, here it is possible for everyone to capture the value or assign a value also.


Example

    public class Test
    {
        public int x = 100;
    }
    Test obj = new Test();
    int a = obj.x; //Getting the old value

    obj.x=200; //Setting a new value


  •  By storing a value in the 'private' variable also access can be given to that value outside of the class by defining a property. The advantage in this option is we can provide access to the value in 3 different ways.


  1. Both Get and Set Access(Read/Write property)
  2. Only Get Access(Read Only property)
  3. Only Set Access(Write Only property)

Syntax
[<modifiers>] <type> <name> 
{ 
[get{<stmts>;} //Get Access 
[set{<stmts>;} //Set Access 

}

  • The code we write under a GetAccessor of the property gets executed whenever we are trying to access the value of a property.

     Example-
        string str = "Hello";
    int len = str.Length;


  • The code in the SetAccessor of the property gets executed when we try to assign a new value to the property.

    Example:
     Console.BackgroundColor=ConsoleColor.Blue;

Note:

  • If the property is defined with both Get and Set accessors it is a Read Write property.
  • If it is defined only with a Get Accessor it is a Read-Only property
  • If it is defined only with a Set Accessor it is a Write-Only property

*Add a class "Customer.cs" and write the following.

    public enum Cities { Hyderabad, Chennai, Bangalore, Mumbai, Calcutta, Delhi };
    public class Customer
    {
        int _custid;
        string _cname, _state, _country;
        double _balance;
        bool _status;
        Cities _city;
        public Customer(int custid)
        {
            this._custid = custid;
            _cname = "Mithilesh";
            _balance = 10000;
            _status = false;
            _city = 0;
            _state = "Telangana";
            _country = "India";
        }

        //ReadOnly Property
        public int Custid
        {
            get { return _custid; }
        }
        //Simple Read/Write Property
        public string Cname
        {
            get { return _cname; }
            set { _cname = value; }
        }
        public bool Status
        {
            get { return _status; }
            set { _status = value; }
        }
        //Read/Write Property with Condition
        public double Balance
        {
            get
            {
                if (_status == true)
                    return _balance;
                return 0;
            }
            set
            {
                if (value == 5000)
                    _balance = value;
            }
        }
        //Enumerated Property
        public Cities City
        {
            get { return _city; }
            set { _city = value; }
        }
        //Setting Scope of property accessors independently(New in C#2.0)
        public string State
        {
            get { return _state; }
            private set { _state = value; }
        }
        //Automatic Property (New in C# 3.0)
        public string Country
        {
            get;
            private set;
        }

     }

Enumerated Properties

These are properties that are defined with a set of constants to choose from. To define an Enumerated property we need to follow the below process.

Step1: Define an "enum" first which should contain all the constant values listed in it, an 'enum' is a type which is going to be a set of constant collection.

Syntax

    [<modifiers>] enum <Name> {<list of Constants>}
    Eg: public enum Days { Monday, Tuesday, Wednesday, Thursday, Friday };

Step2: As an 'enum' is a type to consume a first we need to create an object of it.
Days day = 0; //Initializing with Monday
        (or)
    Days day=Days.Friday;

Step3: Now define a property making using of 'enum' as a property
    public Days Day
    {
        get { return day; }
        set { day = value; }

    }

Features


  • In 2.0 version we were given with an option to set the scope of each Property accessors independently. So that both the blocks can be having different scopes.
            Eg:- state property we have defined above.

  • In C# 3.0 version we were given with a feature automatic property features, which allows us to define a property that doesn't require any variable and also the 'get' and 'set' blocks doesn't require any codes also, but in case of an automatic property it is must the property should define with both 'get' and 'set' blocks.

Ex: - Country property in our above code.

To Consume the properties add a new class "TestCustomer.cs" and write the following.

class TestCustomer
    {
        static void Main()
        {
            Customer obj = new Customer(101);
            Console.WriteLine(obj.Custid);
            //Assignment cannot be performed as property in ReadOnly
            //obj.Custid=102;
            Console.WriteLine(obj.Cname);
            obj.Cname = "Mr.Mithilesh";
            Console.WriteLine(obj.Cname);
            //Balance will be zero as status is inactive
            Console.WriteLine(obj.Balance);
            Console.WriteLine(obj.Status);
            obj.Status = true;
            //Now we can access balance as status is set as Active
            Console.WriteLine(obj.Balance);
            //Assignment fails as balance can't be less than 500
            obj.Balance = 400;
            Console.WriteLine(obj.Balance);
            obj.Balance = 1000;
            //Assignment is Succeeds
            Console.WriteLine(obj.Balance);
            Console.WriteLine(obj.City);
            obj.City = Cities.Mumbai;
            Console.WriteLine(obj.City);
            Console.WriteLine(obj.State);
            //Assigning is not possible because current class is not a child class of Constructor
            //obj.State="UP"; //Invalid
            Console.WriteLine(obj.Country);
            Console.ReadLine();
        }

    }

Indexers


  • These are also very much similar to a 'property' that is used for providing access to values of a class, where properties will be used for accessing Scalar values like int, float, string, etc…, whereas indexers will be used for providing access to Arrays of a class.
  • We define an Indexer very much similar to property but an Indexer will not have any name. We use 'this' keyword as a name to Indexer.
  • After defining an Indexer the object of the class starts behaving like an array providing access to values of the Array present inside it.


*Add a class "IndexerDemo.cs" and write the following.

  class IndexerDemo
    {
        //Declaring a private Array
        string[] arr;
        public IndexerDemo(int size)
        {
            //Initializing the Array under Constructor
            arr = new string[size];
            //Assigning default values to Array
            for (int i = 0; i < size; i++)
                arr[i] = "Empty";
        }
        //Declaring Indexers to provide access for array values outside the class
        public string this[int index]
        {
            get { return arr[index]; }
            set { arr[index] = value; }
        }

    }

*Add a class "TestIndexer.cs" and write the following
    class TestIndexer
    {
        static void Main()
        {
            IndexerDemo obj = new IndexerDemo(6);
            for (int i = 0; i < 6; i++)
                Console.WriteLine(obj[i] + "");
            Console.WriteLine();
            obj[0] = "India";
            obj[2] = "USA";
            obj[4] = "Hyderabad";
            for (int i = 0; i < 6; i++)
                Console.WriteLine(obj[i] + "");
            Console.ReadLine();
        }

    }

No comments: