Ari Lotter
Ari Lotter

Reputation: 615

Access a private variable

I'm modding a game, and I've run across a problem. I'm trying to draw text to the screen in C# with .NET and XNA, so i'm using XNA's SpriteBatch.

The problem is, I can't modify any source files. I can only load external .cs files. I can LOOK at the source, and the variable is defined as so in the class Main.cs:

private SpriteBatch spriteBatch;

If I define my own SpriteBatch as so:

public SpriteBatch spriteBatch;

then it doesn't draw, because I don't have a draw method. Now, all I want to do is access Main.spriteBatch, but that variable is private as mentioned before.

Any ideas?

Upvotes: 0

Views: 2230

Answers (2)

N_A
N_A

Reputation: 19897

You can use reflection to retrieve the value of private variables or methods.

http://www.csharp-examples.net/reflection-examples/

namespace Test
{
    public class Calculator
    {
        public Calculator() { ... }
        private double _number;
        public double Number { get { ... } set { ... } }
        public void Clear() { ... }
        private void DoClear() { ... }
        public double Add(double number) { ... }
        public static double Pi { ... }
        public static double GetPi() { ... }
    }
}

Calculator calc = new Calculator();

// invoke private instance method: private void DoClear()
calcType.InvokeMember("DoClear",
    BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.NonPublic,
    null, calc, null);

To invoke with arguments, pass a array of the arguments in instead of null.

Link to further documentation from the msdn.

Upvotes: 2

Frazell Thomas
Frazell Thomas

Reputation: 6111

You could use reflection to access the private member, but this isn't a recommended practice to actually use. The internal implementation of objects is subject to change and accessing them is a violation of good OOP principal.

The similar answer here will help you accomplish the task though:

Can I change a private readonly field in C# using reflection?

Upvotes: 0

Related Questions