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");
Related
I am trying to use reflection for getting the property name declared and its value, I am able to get the declared property name using property info the main concern I am having is I want to get the value for the property and I don't know the object type so I cant cast directly.
I know we need to use item.GetValue(object) but here the object, I need to pass using reflection.
For example, if you see the below code
Class structure
public abstract class ObjectInputs{}
public class ValveInputs : ObjectInputs
{
public Conditions Conditions { get; set; } = new Conditions();
}
public class Conditions :IExportable
{
[CanExportAttribute]
public string north {get;set;}
}
Method
public void Append(Scenario scenario)
{
var scenarioInputs = (commonDomain.ObjectInputs)scenario.Inputs; // ObjectInputs is an abstract class
var exportableInputs = scenarioInputs.GetType().GetProperties().Where(x =\> typeof(IExportable).IsAssignableFrom(x.PropertyType)); // I extraced property having interface IExportable
var listOfExportableProperties = new ScenarioExtract();
foreach (var exportableInput in exportableInputs)
{
var allProperties = ((System.Reflection.TypeInfo)exportableInput.PropertyType).DeclaredProperties; // Got all the property details
var propertyHavingAttribute = allProperties.Where(x =\> x.CustomAttributes.Where(z =\> z.AttributeType == typeof(CanExportAttribute)).Any()).ToArray(); // Got the properties which i need to extract.
The issue is here, if i do this then its creating a new instance and the values of each properties are set to default. I want to cast the exportableInput to its type (I cant hard code the type casting) so that i can use the value below.
object destination = Activator.CreateInstance(scenarioInputs.GetType());
foreach (var item in propertyHavingAttribute)
{
var detail = new InputPropertyDetail { InputName = item.Name, InputValue = \*\*item.GetValue(destination).ToString() \*\*}; \*\*want to use value here\*\*
listOfExportableProperties.PropertyDetails.Add(detail);
}
}
spreadsheetBuilder.AppendComponenet(listOfExportableProperties);
}
If you're using Activator.CreateInstance, it will always create a new instance (as the name inplies) with default values. Instead you must use the value of the exportableInput property.
object destination = exportableInput.GetValue(scenarioInputs);
Then you can get the actual value of the exportable property of the instance with InputValue = item.GetValue(destination).ToString().
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.
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);
}
}
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)
Lets say i have this class:
class Test123<T> where T : struct
{
public Nullable<T> Test {get;set;}
}
and this class
class Test321
{
public Test123<int> Test {get;set;}
}
So to the problem lets say i want to create a Test321 via reflection and set "Test" with a value how do i get the generic type?
Since you are starting from Test321, the easiest way to get the type is from the property:
Type type = typeof(Test321);
object obj1 = Activator.CreateInstance(type);
PropertyInfo prop1 = type.GetProperty("Test");
object obj2 = Activator.CreateInstance(prop1.PropertyType);
PropertyInfo prop2 = prop1.PropertyType.GetProperty("Test");
prop2.SetValue(obj2, 123, null);
prop1.SetValue(obj1, obj2, null);
Or do you mean you want to find the T?
Type t = prop1.PropertyType.GetGenericArguments()[0];
This should do it more or less. I have no access to Visual Studio right now, but it might give you some clue how to instantiate the generic type and set the property.
// Define the generic type.
var generic = typeof(Test123<>);
// Specify the type used by the generic type.
var specific = generic.MakeGenericType(new Type[] { typeof(int)});
// Create the final type (Test123<int>)
var instance = Activator.CreateInstance(specific, true);
And to set the value:
// Get the property info of the property to set.
PropertyInfo property = instance.GetType().GetProperty("Test");
// Set the value on the instance.
property.SetValue(instance, 1 /* The value to set */, null)
Try something like this:
using System;
using System.Reflection;
namespace test {
class Test123<T>
where T : struct {
public Nullable<T> Test { get; set; }
}
class Test321 {
public Test123<int> Test { get; set; }
}
class Program {
public static void Main() {
Type test123Type = typeof(Test123<>);
Type test123Type_int = test123Type.MakeGenericType(typeof(int));
object test123_int = Activator.CreateInstance(test123Type_int);
object test321 = Activator.CreateInstance(typeof(Test321));
PropertyInfo test_prop = test321.GetType().GetProperty("Test");
test_prop.GetSetMethod().Invoke(test321, new object[] { test123_int });
}
}
}
Check this Overview of Reflection and Generics on msdn.