Simon Price
Simon Price

Reputation: 3261

c# enumerate values from new instance of a class

I asked a question on here earlier but I didn't explain correctly so I got the right answers to the wrong question.

I am creating an instance of a class, when I get the class back it returns a number of results which are private in the class I am calling.

I am unable to change this class and make them public for various reasons.

What I need to do is enumerate through and get a value of the Text variable that is held:

public class StringReader
{

    private string LongText = "this is the text i need to return";
    private string Text;

    public StringReader()
    {

        Text = LongText;
    }
}

In the method I am trying to get the value of Text I am calling

 StringReader sReader = new StringReader();
 List<StringReader> readers = new List<StringReader>() { sReader};

Readers has LongText and Text but I am struggling to get the text value back.

Instead it just returns the Type to me.

Upvotes: 0

Views: 66

Answers (3)

Draken
Draken

Reputation: 3189

Without modifying the class, it's impossible using best OOP practices. They are set to private to mean they can only be accessible inside the class only. You need to speak to the original developer of the class and ask why they cannot make a public getter for the private field that would look like this:

public string getText(){
    return this.Text;
}

This would mean the string can't be modified, but you can at least read it.

Upvotes: 0

sara
sara

Reputation: 3589

Fields declared as private are inaccessible outside the class that defined them. You cannot read their value without either

  1. Changing their visibility
  2. Adding an accessor method/property with public visibility
  3. Using reflection (this is not recommended, there is almost always a better way)

What is the use-case here? What are you trying to achieve? If you define your problem a bit more generally maybe we can give a better solution.

Upvotes: 2

Roy T.
Roy T.

Reputation: 9648

You will need to use reflection to access the private field. You can access all fields of a type using the GetField(s) method. You can access their values using the GetValue function

public string GetLongText(StringReader reader)
{
    // Get a reference to the private field
    var field = reader.GetType().GetField("LongText", BindingFlags.NonPublic | 
                         BindingFlags.Instance)

    // Get the value of the field for the instance reader
    return (string)field.GetValue(reader);                 
}

Upvotes: 3

Related Questions