Software & Finance





C# - Data Hiding





Data Hiding is a concept in C#. In C Language Struct can not hide data of its data members. Where as in C#, we got the luxary of hiding data using e different access levels - private, protected, public.

Private members and functions can only be accessed by class members of the class. You can think the data abstraction is also using data hiding techniques. Protected members can be accessed only by the class and its derived classes.

 

In this sample code, the class CStudent members variables such as name, age, addr1, etc can not be accessed directly. You need to go through the interfaces functions to access these members.


 

Source Code


using System;

using System.Collections.Generic;

using System.Text;

 

namespace DataHidingSample

{

 

      class DataHiding

      {

        public class CStudent

        {

            private String name;

            private int age;

            private String addr1;

            private String addr2;

            private String city;

            private String zipcode;

 

            public CStudent() { }

 

            public String GetName() { return name; }

            public String GetAddr1() { return addr1; }

            public String GetAddr2() { return addr2; }

            public String GetCity() { return city; }

            public String GetZipCode() { return zipcode; }

            public int GetAge() { return age; }

 

            public void SetName(String s) { name = s; }

            public void SetAddr1(String s) { addr1 = s; }

            public void SetAddr2(String s) { addr2 = s; }

            public void SetCity(String s) { city = s; }

            public void SetZipCode(String s) { zipcode = s; }

            public void GetAge(int v) { age = v; }

        };

 

        static void Main()

        { 

            CStudent s = new CStudent();

            // s.name = "softwareandfinance.com"; // CStudent.name' is inaccessible due to its protection level

            s.SetName("softwareandfinance.com");

            System.Console.WriteLine(s.GetName());

        }

    } 

}

Output


softwareandfinance.com