C # Object-oriented encapsulation

Source: Internet
Author: User

Encapsulation refers to hiding the internal data of a class from being manipulated directly by an object instance, and in C # provides a property mechanism to manipulate the state inside the class.

Encapsulation in C # can be represented by keywords such as public, private, protected, and internal.

Why encapsulate the inside of a class?

Cases:

public class Person

{

public string name;

public int age;

}

If I instantiate this class above

Person P=new person ()

So I assign a negative to age, which is clearly not in line with the business logic, is the person's age likely to be negative?

P.age= "-1"

After using encapsulation

public class Person

{

private string name;

public string Name

{

Get{return name;}

Set{name=value;}

}

private int age;

public string Age

{

Get{return age;}

set{

if (value>0)

{

Age=value; The age is controlled, and the age must be greater than 0 to assign a value. Then the age of 1 is not assignable.

}

Else

{

Throw (New ArgumentException ("Error", Value, "Age cannot be negative"));//Throws an exception here

}

}

}

}

Once encapsulated, the object instance can only manipulate properties, and the properties may be controlled by writing down their own logic.

C # Object-oriented encapsulation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.