Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing C# property name or attributes

Tags:

c#

properties

I would like to automatically generate SQL statements from a class instance. The method should look like Update(object[] Properties, object PrimaryKeyProperty). The method is part of an instance (class, base method - generic for any child). Array of properties is an array of class properties, that will be used in update statement. Property names are equal to table field names.

The problem is that I can't get property names.

Is there any option to get a property name inside class instance? sample:

public class MyClass {
public int iMyProperty { get; set; }
public string cMyProperty2 { get; set; }
{

main() {
 MyClass _main = new MyClass();

_main.iMyProperty.*PropertyName* // should return string "iMyProperty"

{

I am aware of PropertyInfo, but I don't know hot to get the ID of a property from GetProperties() array.

Any suggestion?

like image 962
FrenkR Avatar asked Sep 10 '09 20:09

FrenkR


People also ask

How do I access administrative share?

To do it, follow these steps: Click Start, click Run, type cmd, and then press ENTER. At the command prompt, type net share, and then press ENTER. Look for the Admin$, C$, and IPC$ administrative shares in the list of shares.

How do I access C drive remotely from command prompt?

Step 1. Search cmd in the search box and then right-click the option, choose “Run as Administrator”. Step 2. Type “mstsc” and then press the “Enter” key to open Remote Desktop.


2 Answers

Just wrote an implementation of this for a presentation on lambdas for our usergroup last Tuesday.

  • You can do

    MembersOf<Animal>.GetName(x => x.Status)

  • Or

    var a = new Animal() a.MemberName(x => x.Status)

the code:

public static class MembersOf<T> {
    public static string GetName<R>(Expression<Func<T,R>> expr) {
        var node = expr.Body as MemberExpression;
        if (object.ReferenceEquals(null, node)) 
            throw new InvalidOperationException("Expression must be of member access");
        return node.Member.Name;
    }
}
  • Link to the presentation and code samples.
  • Also in SVN (more likely to be updated): http://gim-projects.googlecode.com/svn/presentations/CantDanceTheLambda
like image 164
George Mauer Avatar answered Oct 06 '22 14:10

George Mauer


I found a perfect solution in This Post

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

And then for the usage :

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

Works like a charm

like image 29
Mehdi LAMRANI Avatar answered Oct 06 '22 14:10

Mehdi LAMRANI