vijay

welcome Netizen

Share Your Knowledge.It is a way to achieve immortality

Friday, December 21, 2012

Encapsulation in C#


Main concept of encapsulation is data hiding or information hiding.
Encapsulation provides the ability to hide the internal details of an object from its users. The outside user may not able to change the state of the object directly. Inside the state of the object altered directly by using access modifier keyword public, private and protected.
Just I illustrate with one example.
Take once class, inside the class write the logic to check the enter age from the user. This logic has been implemented in the class the derived class may not know the logic i.e. called as data hiding.
Class A
   private String studname;
    private int studage;

    public string name
    {
        get
        {
            return studname;
        }
        set
        {
            studname = value;
        }
    }
    public int age
    {
        get
        {
            return studage;
        }
        set
        {
            if (value <= 18)
            {
                throw new Exception("Invalid age");
               
            }           
                studage = value;
                      
        }

    }

In an another class use the class A, when u enter the age less than 18 then it will throw the exception error

  try
        {
            ClassA obj = new ClassA();
            obj.age = 22;
            int rrr = obj.age;
            obj.name = "tr";
            Response.Write(rrr);
        }
        catch (Exception ex)
        {
            Response.Write(ex);
        }


 That’s it I hope you understood the concept behind on the encapsulation in oops
Post your feedback………

0 comments:

Post a Comment