We can access private variable of a class in a different class in so many ways. Here is some of them:
- 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;
- public void DisplayVariable()
- {
- Console.Write("The Value of Private Variable=" + i);
- }
- }
- class DisplayPrivateVariable
- {
- static void Main()
- {
- PrivateVariable objPrivateVariable = new PrivateVariable();
- objPrivateVariable.DisplayVariable();
- }
- }
- }
- 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.
Example:
- 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();
- }
- }
- }
- }
- }
- By Using Properties
By using properties also we can do the same work as previous.
Example:
- 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();
- }
- }
- }