Accessing property through string name [duplicate] - c#

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to set object property through Reflection
If I have the following program:
public class MyClass
{
public int MyIntProp {
get;
set;
}
public string MyStringProp {
get;
set;
}
}
public class MyMainClass
{
private const string PropertyName = "MyIntProp";
private MyClass _myClass;
public MyMainClass()
{
_myClass = new MyClass();
// _myClass.PropertyName = 5;
}
}
What I want to do is be able to assign a value of 5 to the MyIntProp property. Is it possible to do this using a string name? I though I saw something like this done before using LINQ, but I can't seem to remember the syntax or where I found it.

You can use Reflection with GetProperty method:
typeof(MyClass).GetProperty(PropertyName).SetValue(_myClass, 5);

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 assign a value to an enum? [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 3 years ago.
Trying to assign a value to the _cat.CatType.
I was wondering how to do this without getting a null reference error?
using System;
public class Program
{
private CatClass _cat;
public void Main()
{
_cat.CatType = CatType.Active;
Console.WriteLine(_cat.CatType.ToString());
}
public enum CatType
{
New,
Active,
Inactive
}
public class CatClass
{
public CatType CatType
{
get;
set;
}
}
}
Ideally I want to assign it something like this _cat.CatType = CatType.Active
You need to initialise it with the new keyword
Used to create objects and invoke constructors
public void Main()
{
_cat = new CatClass();
_cat.CatType = CatType.Active;
Console.WriteLine(_cat.CatType.ToString());
}
You need to create an instance of the class.
private CatClass _cat = new CatClass;
Instantiate _cat with the new keyword first:
_cat = new CatClass
{
CatType = CatType.Active
};

Do properties implicitly initialise variables? [duplicate]

This question already has answers here:
Do properties always have a value when unset?
(4 answers)
Closed 4 years ago.
I found this code on a PDF tutorial:
public class Chien
{
public static int NombreDeChiens { get; set; }
private string prenom;
public Chien(string prenomDuChien)
{
prenom = prenomDuChien;
NombreDeChiens++;
}
public void Aboyer()
{
Console.WriteLine("Wouaf ! Je suis " + prenom);
}
}
There is no initialization in this code though in the constructor there is this incrementation. So how is it possible?
A property is nothing but a field wrapped with a get- and a set-method. As fields do have an initial value, properties also do.
E.g. the following code:
public int MyProperty { get; set; }
is translated to something like this by the compiler:
private int _myProperty; // the actual name of the field defers and is only known by the compiler
public int get_MyProperty() { return this._myProperty; }
public void set_MyProperty(int value) { this._myProperty = value; }
So the question boils down to "have fields a default-value"? The answer to this question is yes, they do: null for reference-types and the default-value for all structs, e.g. 0 for int, or 0f for float.

How to copy a class object in C# [duplicate]

This question already has answers here:
How do you do a deep copy of an object in .NET? [duplicate]
(10 answers)
Creating a copy of an object in C# [duplicate]
(4 answers)
Closed 5 years ago.
As per my understanding in C#, when an object is assigned to another object of same type, its reference is copied instead of the value. So I would like to know how to assign an object to another object such that its values are copied and not referenced to the second object..
You can see that test2.ErrorDetail is changed to "DTL2", while test1.ErrorDetail remains "DTL1".
public class TestClone : ICloneable
{
public bool IsSuccess { get; set; }
public string ErrorCode { get; set; }
public string ErrorDetail { get; set; }
public object Clone()
{
return this.MemberwiseClone();
}
}
static void Main(string[] args)
{
var test1 = new TestClone() { IsSuccess = true, ErrorCode = "0", ErrorDetail = "DTL1" };
var test2 = (TestClone) test1.Clone();
test2.ErrorDetail = "DTL2";
}
You have to clone an object instead of assigning a reference.

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