How to get class members values having string of their names? [duplicate] - c#

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How can I read the properties of a C# class dynamically?
I have to get values of class members using strings of their names only. I think I have to use Reflection but I am not realy sure how to. Can you help me?

MemberInfo member = typeof(MyClass).GetMember("membername");
GetMember reference.
If you know type of member you're looking for, you can use .GetMethod, .GetField, .GetProperty, etc.
If you don't know the type you are working with:
var myobject = someobject;
string membername = "somemember";
MemberInfo member = myobject.GetType().GetMember(membername);
Different member types have different means to getting the value. For a property you would do:
var myobject = someobject;
string propertyname = "somemember";
PropertyInfo property = myobject.GetType().GetProperty(membername);
object value = property.GetValue(myobject, null);

public class Foo
{
public string A { get; set; }
}
public class Example
{
public void GetPropertyValueExample()
{
Foo f = new Foo();
f.A = "Example";
var val = f.GetType().GetProperty("A").GetValue(f, null);
}
}

Related

How to get value of variable from selected class In c#? [duplicate]

This question already has answers here:
How to get a property value based on the name
(8 answers)
Closed 2 years ago.
I want to get the value of a desired variable among several variables in a class
When i put string and class in Method, the method returns the value of the variable with the same name as the string received among all variables included in the class.
This method can get any type of class. So this method need to use generic.
Do anyone have a good idea for my problem?
public class A
{
public int valA_int;
public string valA_string;
public float valA_float;
public long valA_long;
}
public class B
{
public int valB_int;
public string valB_string;
public float valB_float;
public long valB_long;
}
public static class Method {
public static object GetvalueFromClass<T>(string varName, T classType) {
//Find val from class
return object;
}
}
public class Program {
public A aClass;
public B bClass;
public void MainProgram() {
object valA_int = Method.GetvalueFromClass("valA_int", aClass);
object valB_long = Method.GetvalueFromClass("valB_long", bClass);
}
}
The concept of method is like this.
please help me to figure out my problem.
your task already defined.
if you use
#{Class}.GetType().GetProperty(#{VariableName}).GetValue(#{DefinedClass}, null);
you can easily get variable from your class with variable name.
it returns variable as object. so you need to convert it
Example code
CLASS YourClass = [A CLASS WHICH IS PRE DEFINED];
object Target = YourClass.GetType().GetProperty("YOUR VARIABLE").GetValue(YourClass , null);
ok, use reflection to get all the variables in the object, then run through a loop checking them against the string of the property name. From there you should be able to return the value.
So something like
public object FindValByName(string PropName)
{
PropName = PropName.ToLower();
var props = this.GetType().GetProperties();
foreach(var item in props) {
if(item.Name.ToLower() == PropName) {
return item.GetValue(this);
}
}
}

How to get variable name such as nameof(this) [duplicate]

This question already has answers here:
get name of a variable or parameter [duplicate]
(3 answers)
Closed 6 years ago.
How to get variable name of this?
var thename = new myclass();
Whereas I want the variable name "thename" inside myclass instance?
What do you expect in the following scenario?
var theName = new MyClass();
var otherName = theName;
someList.Add(otherName);
The name(s) you're after don't belong to the instance but to the variables referencing it.
There are now three references pointing to the same instance. Two have distinct names, the third does not really have a name.
Inside a MyClass object, you can't know who's pointing at you. Heap objects themselves are always anonymous.
public class myclass()
{
public string VariableName { get; set; }
}
var theName = new myclass();
theName.VariableName = nameof(theName);
Instantiating the variable like this, it doesn't exist to have a name before you create the object. If you want to force every instance to populate that variable, then you can do something like this, but your code will be a little more verbose:
public class myclass()
{
public myclass(string variableName)
{
if (string.IsNullOrWhitespace(variableName)
{
throw new ArgumentNullException(nameof(variableName);
}
VariableName = variableName;
}
public string VariableName { get; private set; }
}
myclass theName;
theName = new myclass(nameof(myclass));
Of course, there's no guarantee that someone isn't passing in a different string.

Serialize and deserialize a hierarchy of a C# class to Json [duplicate]

This question already has answers here:
Using Json.NET converters to deserialize properties
(9 answers)
Closed 6 years ago.
Is there a way to serialize and then deserialize a class that has a member variable of unknown type that could be either be a simple value type or an instance of the containing class itself ?
public class A
{
public dynamic Value { get; set; }//Value could be int or type A for example
}
public static class ASerializer
{
public static string ToJson(A table)
{
return JsonConvert.SerializeObject(table);//using Json.Net
}
public static A FromJson(string json)
{
return JsonConvert.DeserializeObject<A>(json);
}
}
public class Tests
{
public static void TestASerialization()
{
var a = new A() { Value = 1 };
var aa = new A { Value = a };
var aaa = new A { Value = aa };
var json = ASerializer.ToJson(aaa);
var aaa2 = ASerializer.FromJson(json);
var aa2 = (A)aaa2.Value; //throws
}
}
if I serialize and then deserialize aaa - I can't cast the Value of the deserialized aaa back to type A I get:
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException : Cannot convert type 'Newtonsoft.Json.Linq.JObject' to
'A'
Any suggestions on handling this nested hierarchy elegantly, without resorting to hand coding ?
Seems to work with just one instance of A with Value of type A.
You aren't casting what you think you're casting.
In this case, you're actually casting the Value property to A. You need to wrap the aaa2 instance in params with the cast before accessing the property.
var aa2 = ((A)aaa2).Value;
Dynamic is a compiler hack mostly, I would recommend generics instead.
#David L 's answer is also correct.
public class A<T>
{
public T Value { get; set; }
}

how to populate an instance created by Activator.CreateInstance() method [duplicate]

This question already has answers here:
Set object property using reflection
(10 answers)
Closed 8 years ago.
class Program
{
static void Main()
{
testclass tc = new testclass();
Type tt = tc.GetType();
Object testclassInstance = Activator.CreateInstance(tt);
PropertyInfo prop = tt.GetProperty("name");
MethodInfo MethodName = tt.GetMethod("set_" + prop.Name);
string[] parameters = new string[2];
parameters[0] = "first name of the bla bla";
MethodName.Invoke(testclassInstance, parameters);
Console.WriteLine(testclassInstance.GetType().GetProperty("name").GetValue(testclassInstance, null));
Console.ReadLine();
}
}
class testclass
{
public string name { get; set; }
}
output error message is:
Parameter count mismatch
i don't want to create constructor for testclass and pass parameters/populate like that. i want to populate its properties one by one.
plz link other useful instance populating methods. i know this is the silliest one.
Check out this question: how to create an instance of class and set properties from a Bag object like session
Type myType = Type.GetType(className);
var instance = System.Activator.CreateInstance(myType);
PropertyInfo[] properties = myType.GetProperties();
foreach (var property in properties)
{
if (property.CanWrite)
{
property.SetValue(instance, session[property.Name], null);
}
}
It is as easy as:
prop.SetValue(testclassInstance, "first name of the bla bla");

Update a class property using reflection and the name of the property as a string [duplicate]

This question already has answers here:
Set object property using reflection
(10 answers)
Closed 9 years ago.
I have a sample class
public class sampleClass
{
public string givenName { get; set; }
public string familyName { get; set; }
}
and a set of values for that class contained in IDictionary<string, object> dataModel. I can use reflection to iterate through the dataModel and use the dataModel key to get the value.
I would like to do something like:
void UpdateValues(IDictionary<string, object> dataModel)
{
Type sourceType = typeof(sampleClass);
foreach (PropertyInfo propInfo in (sourceType.GetProperties()))
{
if (dataModel.ContainsKey(propInfo.Name))
{
// set propInfo value here
propInfo.Value = dataModel[propInfo.Name];
}
}
}
But i have no idea how to do the line
propInfo.Value = dataModel[propInfo.Name];
Help! Thanks !!
you need an instance of the sampleClass to set the property on and then you can use the SetValue function to do that:
propInfo.SetValue(yourinstance, dataModel[propInfo.Name], null);
see this URL: http://msdn.microsoft.com/en-us/library/axt1ctd9.aspx
propInfo.SetValue(sampleClass, dataModel[propInfo.Name], null)

Categories