Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

An interview riddle: accessing a private data member [duplicate]

I recently had an interview with C# questions. One of them I cannot find an answer to.

I was given a class, looks like this:

public class Stick
{
    private int m_iLength;
    public int Length
    {
        get
        {
            return m_iLength;
        }
        set
        {
            if (value > 0)
            {
                m_iLength = value;
            }
        }
    }
}

Also, a main class was given

static void Main(string[] args)
{
    Stick stick = new Stick();
}

The task was to add code to the main that will cause m_iLength in the Stick class to be negative (and it was stressed out that it can be done).

I seem to miss something. The data member is private, and as far as I know the get and set function are by value for type int, so I do not see how this can be done.

like image 612
IdoZ Avatar asked Aug 25 '16 06:08

IdoZ


1 Answers

Reflection is always the most direct:

var type = typeof(Stick);
var field = type.GetField("m_iLength", BindingFlags.NonPublic |BindingFlags.GetField | BindingFlags.Instance);
field.SetValue(stick, -1);
Console.WriteLine(stick.Length);

Explanation:

The first line gets the Type object for Stick, so we can get the private fields later on.

The second line gets the field that we want to set by its name. Note that the binding flags are required or field will be null.

And the third line gives the field a negative value.

like image 51
Sweeper Avatar answered Oct 15 '22 22:10

Sweeper