Setting/Getting the Class Properties by String Name

Setting/getting the class properties by string name

You can add indexer property, a pseudocode:

public class MyClass 
{
public object this[string propertyName]
{
get
{
// probably faster without reflection:
// like: return Properties.Settings.Default.PropertyValues[propertyName]
// instead of the following
Type myType = typeof(MyClass);
PropertyInfo myPropInfo = myType.GetProperty(propertyName);
return myPropInfo.GetValue(this, null);
}
set
{
Type myType = typeof(MyClass);
PropertyInfo myPropInfo = myType.GetProperty(propertyName);
myPropInfo.SetValue(this, value, null);
}
}
}

C# get and set property by variable name

Yes, your looking for the PropertyInfo.SetValue method e.g.

var propInfo = info.GetType().GetProperty(propertyName);
if (propInfo != null)
{
propInfo.SetValue(info, value, null);
}

Change the values of an object's properties, depending on the property's name

You can use SetValue:

property.SetValue(myObject, -1, null);

You can read the documentation here.

Load class dynamically get property values one of which is a class

This will do the job - please feel free to provide feedback if something does not work as expected.

I first wanted to use a JsonPath query to find the matching children - but it does not seem to support wildcards for property names. At least I did not find any documentation.

Thus we loop through all child properties to find the ones starting with "season/" - this should be fine from a performance perspective as JsonPath probably would do the same and with that small amount of data it doesn't really matter on a modern system anyways.


static IReadOnlyList<SeasonDetails> GetSeasons(string json)
{
List<SeasonDetails> seasons = new List<SeasonDetails>();
JObject jObject = JObject.Parse(json);
foreach (var child in jObject.Children<JProperty>())
{
if (!child.Name.StartsWith("season/"))
{
continue;
}

seasons.Add(child.Value.ToObject<SeasonDetails>());
}

return seasons;
}

public class SeasonDetails
{
public string _id { get; set; }
public string air_date { get; set; }
public Episode[] episodes { get; set; }
public string name { get; set; }
public string overview { get; set; }
public string poster_path { get; set; }
public int season_number { get; set; }
}

public class Episode
{
public string air_date { get; set; }
public int episode_number { get; set; }
public int id { get; set; }
public string name { get; set; }
public string overview { get; set; }
public string production_code { get; set; }
public int season_number { get; set; }
public string still_path { get; set; }
public float vote_average { get; set; }
public int vote_count { get; set; }
}

Afterwards you can do your logic by looping through the list of seasons:

foreach(SeasonDetails season in seasons) {
// Fill your datatable.
}

How to get/set value of properties using string property paths?

Following method gets values from nested properties:

    public static object GetPropertyValue(object src, string propName)
{
if (src == null) throw new ArgumentException("Value cannot be null.", "src");
if (propName == null) throw new ArgumentException("Value cannot be null.", "propName");

if (propName.Contains("."))//complex type nested
{
var temp = propName.Split(new char[] { '.' }, 2);
return GetPropertyValue(GetPropertyValue(src, temp[0]), temp[1]);
}
else
{
if (src is ExpandoObject)
{
var expando = src as IDictionary<string, object>;

if (expando != null)
{
object obj;
expando.TryGetValue(propName, out obj);
return obj;
}

return null;
}
else
{
var prop = src.GetType().GetProperty(propName);
return prop != null ? prop.GetValue(src, null) : null;
}
}
}

Usage:

 string res1 = GetPropertyValue(root, "BasicDetails.CustomAttributes.phone") as string;
string res2 = GetPropertyValue(root, "BasicDetails.Name") as string;

Get property value from string using reflection

 public static object GetPropValue(object src, string propName)
{
return src.GetType().GetProperty(propName).GetValue(src, null);
}

Of course, you will want to add validation and whatnot, but that is the gist of it.

Set property value using property name

You can try something like this

List<KeyValuePair<string, object>> _lObjects = GetObjectsList(); 
var class1 = new Class1();
var class1Type = typeof(class1);
foreach(KeyValuePair<string, object> _pair in _lObjects)
{
//class have this static property name stored in _pair.Key
class1Type.GetProperty(_pair.Key).SetValue(class1, _pair.Value);
}

Setting a property by reflection with a string value

You can use Convert.ChangeType() - It allows you to use runtime information on any IConvertible type to change representation formats. Not all conversions are possible, though, and you may need to write special case logic if you want to support conversions from types that are not IConvertible.

The corresponding code (without exception handling or special case logic) would be:

Ship ship = new Ship();
string value = "5.5";
PropertyInfo propertyInfo = ship.GetType().GetProperty("Latitude");
propertyInfo.SetValue(ship, Convert.ChangeType(value, propertyInfo.PropertyType), null);


Related Topics



Leave a reply



Submit