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.
-
If you give more information about why you need to access it and why it is declared private etc, you'll probably get better answers. – Hans Olsson Mar 18 '11 at 11:41
-
if it were possible why privates will exist ? – Felice Pollano Mar 18 '11 at 11:42
6 Answers
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.
- Expose the private item via an accessor (requires the code)
- Use reflection to poke around in the object and find it (see here)

- 1
- 1

- 43,770
- 11
- 86
- 103
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
}
}

- 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
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.

- 6,228
- 1
- 22
- 18
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.

- 21,454
- 43
- 116
- 176