2

In class A I am have a private variable that I want to access it from another class. Is it possible? Give me the solution.

Ebrahim Ghasemi
  • 5,850
  • 10
  • 52
  • 113
kajal
  • 29
  • 1
  • 2

6 Answers6

2

The private variable is supposed to be private, so there's no direct way to do this. There are a couple of things you could do.

  1. Expose the private item via an accessor (requires the code)
  2. Use reflection to poke around in the object and find it (see here)
Community
  • 1
  • 1
Jeff Foster
  • 43,770
  • 11
  • 86
  • 103
2

If you want to access it from "outside" you will have to make it public. But better would be to wrap a property around it. Then you could even give readonly access.

public class MyClass
{
   private int myPrivateInt;

   public int PublicInt
   {
     get { return myPrivateInt; }
     set { myPrivateInt = value; } // or remove this line for readonly access
   }
}
Hans Kesting
  • 38,117
  • 9
  • 79
  • 111
  • You don't need the private var in modern .NET versions. ;) `public class MyClass { public int PublicInt { get; set; // or remove this line for readonly access } }` – Alex Mar 18 '11 at 11:52
  • @Alex - I know, I was just showing how you could publish an existing local variable. – Hans Kesting Mar 18 '11 at 12:29
0

I don't think you can access a private variable from another class.

Anuraj
  • 18,859
  • 7
  • 53
  • 79
0

The whole purpose of the "private" access modifier is to prevent this. I think you're looking for moving the variabele to a shared base class or using the "internal" access modifier to restrict accessibility to the classes in the same assembly.

If you really want to access it you can use reflection, but that's something you should try as a last resort. For example, if you use it to access private things in a 3th party library future versions of that lib (with the same public API) can break your application.

Alex
  • 6,228
  • 1
  • 22
  • 18
0

If you could access them, then there wouldn't not be any point in making them private.

However, in practice, get, set are usually implemented if you need access to such members.

Shamim Hafiz - MSFT
  • 21,454
  • 43
  • 116
  • 176
-1

Um...it is called private for a reason. Make it public?

anothershrubery
  • 20,461
  • 14
  • 53
  • 98