I ran into a problem that I need to access to private field of a class. For example:
class MyClass
{
private string someString;
public MyClass( string someStringValue )
{
someString = someStringValue;
}
}
How can I get the value of someString outside MyClass ?
Update:
Sorry, I cannot use property here since the the actual production code is protected. I’m a QA/Dev, I need a way to get those private for writing User Acceptance Test. So I cannot change production code. Can you help?
As others have said, since the field is private you should not be trying to get it with normal code.
The only time this is acceptable is during unit testing, and even then you need a good reason to do it (such as setting a private variable to null so that code in an exception block will be hit and can be tested).
You could use something like the method below to get the field:
So you could call this like:
Again, this should not be used in most cases.