Encapsulation in C#

In this article we are going to see, Encapsulation in C#. So, What is an Encapsulation in C#? The answer is very simple, Encapsulation is nothing but wrapping up of data or members in order to protect them or secure them. Following is a simple program to understand it.

Code Snippet:-

using System;

public class Class1
{
public void Method1()
{
 Console.WriteLine("Calling this Method1 by using Object of Class1.Becauseit is non static.");
}
}

public static class Class2
{
public static void Method2()
{
Console.WriteLine("Calling this Method2 by using name of Class2. Because it is static.");
}
}

public class Encapsulation
{
public static void Main(string[] args)
{
// Creating object of Class1
Class1 object1 = new Class1();
// Calling Method/Data Member of Class1 using its object.
object1.Method1();
// Calling Method2 using Class2 name because it is static.It means, it is sharable.
Class2.Method2();
Console.ReadLine();
}
}


In the above example as we can see, We have to create Object to access data members(“Method1”) of Class1. Same with Class2 also we have to use Class name to access its data member (“Method2”). Because both classes have wrapped their Data Members and protecting from any direct access.









Comments

Popular posts from this blog

How to Transpose DataTable in C# ?

Multiple Inheritance in C#

Process Template Editor Extension Tool in Visual Studio Integration Tutorial