Get String Name of Property Using Reflection

Get string name of property using reflection

If you already have a PropertyInfo, then @dtb's answer of using PropertyInfo.Name is the right way. If, however, you're wanting to find out which property's code you're currently in, you'll have to traverse the current call stack to find out which method you're currently executing and derive the property name from there.

var stackTrace = new StackTrace();
var frames = stackTrace.GetFrames();
var thisFrame = frames[0];
var method = thisFrame.GetMethod();
var methodName = method.Name; // Should be get_* or set_*
var propertyName = method.Name.Substring(4);

If you don't have a PropertyInfo object, you can get that from a property expression, like this:

public static string GetPropertyName<T>(Expression<Func<T>> propertyExpression)
{
return (propertyExpression.Body as MemberExpression).Member.Name;
}

To use it, you'd write something like this:

var propertyName = GetPropertyName(
() => myObject.AProperty); // returns "AProperty"

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 to get current property name via reflection?

Since properties are really just methods you can do this and clean up the get_ returned:

class Program
{
static void Main(string[] args)
{
Program p = new Program();
var x = p.Something;
Console.ReadLine();
}

public string Something
{
get
{
return MethodBase.GetCurrentMethod().Name;
}
}
}

If you profile the performance you should find MethodBase.GetCurrentMethod() is miles faster than StackFrame. In .NET 1.1 you will also have issues with StackFrame in release mode (from memory I think I found it was 3x faster).

That said I'm sure the performance issue won't cause too much of a problem- though an interesting discussion on StackFrame slowness can be found here.

I guess another option if you were concerned about performance would be to create a Visual Studio Intellisense Code Snippet that creates the property for you and also creates a string that corresponds to the property name.

Reflection - get attribute name and value on property

Use typeof(Book).GetProperties() to get an array of PropertyInfo instances. Then use GetCustomAttributes() on each PropertyInfo to see if any of them have the Author Attribute type. If they do, you can get the name of the property from the property info and the attribute values from the attribute.

Something along these lines to scan a type for properties that have a specific attribute type and to return data in a dictionary (note that this can be made more dynamic by passing types into the routine):

public static Dictionary<string, string> GetAuthors()
{
Dictionary<string, string> _dict = new Dictionary<string, string>();

PropertyInfo[] props = typeof(Book).GetProperties();
foreach (PropertyInfo prop in props)
{
object[] attrs = prop.GetCustomAttributes(true);
foreach (object attr in attrs)
{
AuthorAttribute authAttr = attr as AuthorAttribute;
if (authAttr != null)
{
string propName = prop.Name;
string auth = authAttr.Name;

_dict.Add(propName, auth);
}
}
}

return _dict;
}

Reflection - get property name

This can be achieved using Expressions:

// requires object instance, but you can skip specifying T
static string GetPropertyName<T>(Expression<Func<T>> exp)
{
return (((MemberExpression)(exp.Body)).Member).Name;
}

// requires explicit specification of both object type and property type
static string GetPropertyName<TObject, TResult>(Expression<Func<TObject, TResult>> exp)
{
// extract property name
return (((MemberExpression)(exp.Body)).Member).Name;
}

// requires explicit specification of object type
static string GetPropertyName<TObject>(Expression<Func<TObject, object>> exp)
{
var body = exp.Body;
var convertExpression = body as UnaryExpression;
if(convertExpression != null)
{
if(convertExpression.NodeType != ExpressionType.Convert)
{
throw new ArgumentException("Invalid property expression.", "exp");
}
body = convertExpression.Operand;
}
return ((MemberExpression)body).Member.Name;
}

Usage:

var x = new ObjectType();
// note that in this case we don't need to specify types of x and Property1
var propName1 = GetPropertyName(() => x.Property1);
// assumes Property2 is an int property
var propName2 = GetPropertyName<ObjectType, int>(y => y.Property2);
// requires only object type
var propName3 = GetPropertyName<ObjectType>(y => y.Property3);

Update: fixed GetPropertyName<TObject>(Expression<Func<TObject, object>> exp) for properties returning value types.

How do you get a C# property name as a string with reflection?

You can use Expressions to achieve this quite easily. See this blog for a sample.

This makes it so you can create an expression via a lambda, and pull out the name. For example, implementing INotifyPropertyChanged can be reworked to do something like:

public int MyProperty {
get { return myProperty; }
set
{
myProperty = value;
RaisePropertyChanged( () => MyProperty );
}
}

In order to map your equivalent, using the referenced "Reflect" class, you'd do something like:

string propertyName = Reflect.GetProperty(() => SomeProperty).Name;

Viola - property names without magic strings.

How can I Get the property by name from type and Set Propert value using reflection in C#

You're almost there; now just call SetValue on the property info:

//1. Create new instance of Student
Student student = new Student();

//2. Get instance type
var getType = student.GetType();

//3. Get property FullName by name from type
var fullNameProperty = getType.GetProperty("FullName",
typeof(string));

//4. Set property value to "Some Name" using reflection
fullNameProperty.SetValue(student, "Some Name");


Related Topics



Leave a reply



Submit