Hi,

Let’s see how encapsulation can be implemented using properties in C#.NET/ASP.NET.
Let’s see the code first.

using System;

public class Student
{
    private int stud_id = -1;

    public int ID
    {
        get
        {
            return stud_id;
        }
        set
        {
            stud_id = value;
        }
    }

    private string stud_name = string.Empty;

    public string Name
    {
        get
        {
            return stud_name;
        }
        set
        {
            stud_name = value;
        }
    }
}

public class StudentManagerWithProperties
{
    public static void Main()
    {
        Student studObj = new Student();

        studObj.ID = 7;
        studObj.Name = "Aamir Khan";

	Console.WriteLine(
            "ID: {0}, Name: {1}",
            studObj.ID,
            studObj .Name);

        Console.ReadKey();
    }
}

Ok. Here Student class has two properties ID & NAME. Also two private variables or fields stud_name & stud_id, both are encapsulated by our ID & NAME properties. And also two accessors for setting and getting values from fields. Set accessor set the value to the field. Note that the ‘value’ used here is the keyword! This value is assigned by calling function. StudentManagerWithProperties uses the ID & NAME properties as we can see.

🙂

 

Leave a Reply

Your email address will not be published. Required fields are marked *

 

 

 

Theme by HermesThemes

Copyright © 2018 CoderzHeaven. All Rights Reserved

Please wait...

Subscribe to our newsletter

Want to be notified when our article is published? Enter your email address and name below to be the first to know.