Using variable as a name [duplicate] - c#

Is there anyway to set the value of a static (private) variable on an object that has not been initialized? The SetValue method requires an instance, but I'm hoping there's a way to get around this.

For static values you can pass null for the instance parameter.
var type = typeof(SomeClass);
var field = type.GetField("SomeField", BindingFlags.NonPublic | BindingFlags.Static);
field.SetValue(null, 42);

could you create a static function that is public and use it to set your private static variable ?

Related

How can I assign a value to a variable by passing a string of its name?

Example:
int XValue;
int YValue;
void AssignValue(string VariableName,int VariableValue)
{
VariableName = VariableValue;
}
void CallAV()
{
AssignValue("XValue", 10);
AssignValue("YValue", 15);
}
So, basically i want to change the value of a variable by knowing its name.
What you're looking for is collectively called Reflection. Specifically, you want to use Type.GetField(). You could do something like this:
void AssignValue(string VariableName, int VariableValue)
{
// Get the non-public instance variable (field)
FieldInfo field = GetType().GetField(VariableName, BindingFlags.NonPublic | BindingFlags.Instance);
// Set the variable's value for this instance of the type
field.SetValue(this, VariableValue);
}

Get private property of a private property using reflection

public class Foo
{
private Bar FooBar {get;set;}
private class Bar
{
private string Str {get;set;}
public Bar() {Str = "some value";}
}
}
If I've got something like the above and I have a reference to Foo, how can I use reflection to get the value Str out Foo's FooBar? I know there's no actual reason to ever do something like this (or very very few ways), but I figure there has to be a way to do it and I can't figure out how to accomplish it.
edited because I asked the wrong question in the body that differs from the correct question in the title
You can use the GetProperty method along with the NonPublic and Instance binding flags.
Assuming you have an instance of Foo, f:
PropertyInfo prop =
typeof(Foo).GetProperty("FooBar", BindingFlags.NonPublic | BindingFlags.Instance);
MethodInfo getter = prop.GetGetMethod(nonPublic: true);
object bar = getter.Invoke(f, null);
Update:
If you want to access the Str property, just do the same thing on the bar object that's retrieved:
PropertyInfo strProperty =
bar.GetType().GetProperty("Str", BindingFlags.NonPublic | BindingFlags.Instance);
MethodInfo strGetter = strProperty.GetGetMethod(nonPublic: true);
string val = (string)strGetter.Invoke(bar, null);
There is a way to slightly simplify Andrew's answer.
Replace the calls to GetGetMethod() + Invoke() with a single call to GetValue() :
PropertyInfo barGetter =
typeof(Foo).GetProperty("FooBar", BindingFlags.NonPublic | BindingFlags.Instance);
object bar = barGetter.GetValue(f);
PropertyInfo strGetter =
bar.GetType().GetProperty("Str", BindingFlags.NonPublic | BindingFlags.Instance);
string val = (string)strGetter.GetValue(bar);
I did some testing, and I didn't find a difference, then I found this answer, which says that GetValue() calls GetGetMethod() with error checking, so there is no practical difference (unless you worry about performance, but when using Reflection I guess that you won't).

How to use GetPropertyValueSafely from CommonLibrary.NET?

When using the CommonLibrary.Net, how does one use the GetPropertyValueSafely() function correctly?
I want to do something like this:
public static string APP_TITLE = ComLib.ReflectionHelper.GetPropertyValueSafely(Application.ProductName);
but I need to add a second parameter, and I don't understand enough yet to know what is asked for. Here is the syntax usage from the documentation file:
public static Object GetPropertyValueSafely(
Object obj,
PropertyInfo propInfo
)
This are the parameter requirements:
Parameters obj Type: System..::..Object Object whose property is to be retrieved.
propInfo Type: System.Reflection..::..PropertyInfo Property name.
So what do I put for object? I tried this, too:
public static string APP_TITLE;
ComLib.ReflectionHelper.GetPropertyValueSafely(APP_TITLE, Application.ProductName);
but that's not the answer either.
I also tried this:
public static string APP_TITLE = ComLib.Reflection.ReflectionUtils.GetPropertyValue((object)APP_TITLE, Application.ProductName).ToString();
...which compiles, but it throws a runtime type error from the library.
Thanks for the help (I'm just starting to get this stuff into my head).
Try something like this:
public static readonly string APP_TITLE = (string)ComLib.ReflectionHelper.GetPropertyValueSafely(new object(),
ComLib.Reflection.ReflectionUtils.GetProperty(typeof(Application), "ProductName"));
NB: Technically, passing new object() to the PropertyInfo's GetValue method should throw a TargetException. However, since this is a static property, it seems to work.

Get value of a public static field via reflection

This is what I've done so far:
var fields = typeof (Settings.Lookup).GetFields();
Console.WriteLine(fields[0].GetValue(Settings.Lookup));
// Compile error, Class Name is not valid at this point
And this is my static class:
public static class Settings
{
public static class Lookup
{
public static string F1 ="abc";
}
}
You need to pass null to GetValue, since this field doesn't belong to any instance:
fields[0].GetValue(null)
You need to use Type.GetField(System.Reflection.BindingFlags) overload:
http://msdn.microsoft.com/en-us/library/4ek9c21e.aspx
For example:
FieldInfo field = typeof(Settings.Lookup).GetField("Lookup", BindingFlags.Public | BindingFlags.Static);
Settings.Lookup lookup = (Settings.Lookup)field.GetValue(null);
The signature of FieldInfo.GetValue is
public abstract Object GetValue(
Object obj
)
where obj is the object instance you want to retrieve the value from or null if it's a static class. So this should do:
var props = typeof (Settings.Lookup).GetFields();
Console.WriteLine(props[0].GetValue(null));
Try this
FieldInfo fieldInfo = typeof(Settings.Lookup).GetFields(BindingFlags.Static | BindingFlags.Public)[0];
object value = fieldInfo.GetValue(null); // value = "abc"

Use reflection to find the name of a delegate field

Let's say that I have the following delegate:
public delegate void Example();
and a class such as the following:
public class TestClass {
Example FailingTest = () => Assert.Equal(0,1);
}
How can I use reflection to get the name "FailingTest"?
So far I have tried:
var possibleFields = typeof(TestClass).GetFields(relevant_binding_flags)
.Where(x => x.FieldType.Equals(typeof(Example)));
foreach(FieldInfo oneField in possibleFields) {
// HERE I am able to access the declaring type name
var className = oneField.ReflectedType.Name; // == "TestClass"
// but I am not able to access the field
// name "FailingTest" because:
var fieldName = oneField.Name; // == "CS$<>9__CachedAnonymousMethodDelegate1"
}
Stepping through in the debugger, I am unable to find a path to the name of the declared field, "FailingTest".
Is that info retained at runtime or is it lost when the anonymous delegate is assigned?
What BindingFlags are you passing to GetFields? I used these:
BindingFlags.NonPublic | BindingFlags.Instance
and I was able to see the name of the field.

Categories