Saturday, 13 February 2016

How To Access Private Variables of a class In another class in C#

          We can access private variable of a class in a different class in so many ways. Here is some of them

1.By using Public Method :-

         We can access a private variable in a different class by putting that variable with in a Public method and calling that method from another class by creating object of that class.

Example:-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class PrivateVariable
{
private int i = 10; //Declaring and initializing a private variable
public void DisplayVariable()
{
Console.Write("The Value of Private Variable=" + i); //Accessing Private variable with in a public methode
}
}
class DisplayPrivateVariable
{
static void Main()
{
PrivateVariable objPrivateVariable = new PrivateVariable();
objPrivateVariable.DisplayVariable(); //Calling the public method
}
}
}

2.By Using Inner class:-

      By using inner class also we can access a private variable of a class in another class. For better understanding have look at the example.

Eample:-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class PrivateVariable2
{
class Outerclass
{
private int i = 10;
private int j = 20;
class Innerclass
{
static void Main()
{
Outerclass objouter = new Outerclass();
int Result=objouter.i+objouter.j;
Console.Write("Sum=" + Result );
Console.ReadLine();
}
}
}
}
}

3.By Using Properties :-

By using properties also we can do the same work as previous.

Examlpe :-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Employee
{
private int _EmpID=1001;
private string _EmpName;
public int EmpID
{
get { return _EmpID; }
}
public string EmpName
{
get { return _EmpName; }
set { _EmpName = "Smith"; }
}
}
class AcessEmployee
{
static void Main()
{
Employee objEmployee = new Employee();
Console.WriteLine("Employee ID: " + objEmployee.EmpID);
Console.WriteLine("Employee old Name: " + objEmployee.EmpName);
objEmployee.EmpName = "Dyne Smith";
Console.WriteLine("Employee New Name: " + objEmployee.EmpName);
Console.ReadLine();
}
}
}


  ************     Thanks For Reading     *************

1 comment: