Interview riddle: private member access

I recently had an interview with C # questions. One of them I can not find the answer.

I was assigned a class that looks like this:

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

A core class was also provided.

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

The task was to add code to the main one, which would cause m_iLength in the Stick class to be negative (and it was emphasized that this could be done).

I think I missed something. The data element is private, and as far as I know, the get and set function has an int value, so I don’t see how this can be done.

+5
source share
1 answer

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 the Stick , so we can get the private fields later.

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

And the third line gives the field a negative value.

+4
source

All Articles