Get Property Value from String Using Reflection

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.

How get property value with reflection in C#

Once you've retrieved the PropertyInfo, you fetch the value with PropertyInfo.GetValue, passing in "the thing you want to get the property from" (or null for a static property).

Here's an example:

using System;
using System.Reflection;

class Program
{
static void Main()
{
DateTime utcNow = DateTime.UtcNow;

PropertyInfo dateProperty = typeof(DateTime).GetProperty("Date");
PropertyInfo utcNowProperty = typeof(DateTime).GetProperty("UtcNow");

// For instance properties, pass in the instance you want to
// fetch the value from. (In this case, the DateTime will be boxed.)
DateTime date = (DateTime) dateProperty.GetValue(utcNow);
Console.WriteLine($"Date: {date}");

// For static properties, pass in null - there's no instance
// involved.
DateTime utcNowFromReflection = (DateTime) utcNowProperty.GetValue(null);
Console.WriteLine($"Now: {utcNowFromReflection}");
}
}

How to get a property value using reflection

Something like this should work:

var value = (string)GetType().GetProperty("SomeProperty").GetValue(this, null);

Get raw value of property attribute using Reflection

Since attribute constructor information are stored as metadata as well you can get the required information by calling the GetCustomAttributesData method. Have a look at this simple example:

class Program
{
[PasswordPropertyText]
public string Password1 { get; set; }

[PasswordPropertyText(true)]
public string Password2 { get; set; }

[PasswordPropertyText(false)]
public string Password3 { get; set; }

static void Main(string[] args)
{
var props = typeof(Program).GetProperties();
foreach(var prop in props)
{
var attributeData = prop.GetCustomAttributesData().First(x => x.AttributeType == typeof(PasswordPropertyTextAttribute));
Console.WriteLine($"{prop.Name}: {(attributeData.ConstructorArguments.Cast<CustomAttributeTypedArgument?>().FirstOrDefault()?.Value ?? true)}");
}
Console.ReadLine();
}
}

Output:

Password1: True
Password2: True
Password3: False

Get property value of a complex type with reflection in c#

You're trying to get the value of a property as if it were a property of string - the first argument to GetValue needs to be the object you're fetching the property from (oldEntity in this case). So you can get the department like this:

object department = oldEntity.GetType().GetProperty("Department").GetValue(oldEntity, null);

To get the Name property (which I hope is a property and not a public field) you need to do the same kind of thing again:

object name = department.GetType().GetProperty("Name").GetValue(department, null);

However, you could do this all somewhat more simply using dynamic typing:

dynamic entity = oldEntity;
string name = entity.Department.Name;

Note that there's no compile-time checking for the Department or Name parts (or that the resulting type is string) but that's the same as for the reflection-based code anyway. The dynamic typing would just do the reflection for you at execution time.

How to get a property value based on the name

return car.GetType().GetProperty(propertyName).GetValue(car, null);

Get property value by string

You could use Reflection to read property names and values. For example to get a list of public properties on a type you could use the GetProperties method:

var properties = typeof(Setting);
foreach (var prop in properties)
{
// here you can access the name of the property using prop.Name
// if you want to access the value you could use the prop.GetValue method
}

Get property value by name using reflection

Look at your Slice class:

public sealed class Slice
{
public readonly double firstName;
public readonly double secondName;
public readonly double thirdName;
...
}

Those aren't properties. They're fields. Either make them properties, or use Type.GetField() instead. Using properties would generally be a better idea, IMO, and needn't be hard. For example, if you just wanted to make them publicly read-only, you could use:

public sealed class Slice
{
public double FirstName { get; private set; }
public double SecondName { get; private set; }
public double ThirdName { get; private set; }
...
}

Alternatively you could declare read-only fields directly, and then expose them via properties. It's a bit more work than using automatically implemented properties, but it removes the potential for setting the property within Slice itself.

(As an aside, do you really have a firstName field of type double? Odd.)

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