Saturday, 28 May 2016

set

Encapsulation allows us to secure date source and data set to external worlds.
It is used to set data to the variable.
You can verify, validate, and check authorization data before store into the data source.
Syntax:

class myClass
{
    private string _name;

    public string Name
    {
        set
        {
            if (!string.IsNullOrWhiteSpace(value))
            {
                _name = value;
            }
            else
            {
                throw new Exception("Invalid string.");
            }
        }
    }
}
Let's take an example and validate property before assign to private field:

using System;

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

        cls.print();
    }
}

class myClass
{
    private string _name;

    public string Name
    {
        set
        {
            if (VerifyString(value))
            {
                _name = value;
            }
            else
            {
                throw new Exception("Invalid string.");
            }
        }
    }

    public bool VerifyString(string str)
    {
        int i=0;
        foreach(char c in str.ToCharArray())
        {
            if(int.TryParse(c.ToString(),out i))
            {
                return false;
            }
        }
        return true;
    }

    public void print()
    {
        if(this._name!=null)
        {
            Console.WriteLine("Name: {0}", this._name);
        }
        else
        {
            Console.WriteLine("Provide a valid string");
        }
    }
}

Output:
Provide a valid string
Press any key to continue…
In above setter example you have seen that before assign value to the private property of myClass verify method verify string if string contain any digits. If string has any digits then it is not assign any value and if it has not any digits it will show string value which is assign.
If you provide only get method to the property then it will be a read only property.
If you provide only set method to the property then it will be a write only property.
Read more about types of property. class properties

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

No comments:

Post a Comment