How to get name of a class property?
Asked Answered
G

6

33

Is there anyway I can get the name of class property IntProperty?

public class ClassName
{
  public static int IntProperty { get { return 0; } }
}

//something like below but I want to get the string of "IntProperty"
ClassName.IntProperty.GetType().Name

Basically what I want to do is to dynamically save property name string into the database, and later on retrieve it from the database and invoke the property dynamically.

Seems like what I am looking for is similar to duck typing I think.

Thanks!

UPDATED:

This is the actual code. This is more like a workflow kind of thing. But each task is defined as property of a class (class is used to group tasks).

public class ApplicationTask
{
    public static Task<string> SendIncompleteNotification
    {
        get
        {
            return new Task<string>
                (
                a => Console.WriteLine("Sample Task")
                , "This is a sample task which does nothing."
                );
        }
    }
}

So, the code will be able to retrieve the full name of the class and property something like: namespace.ApplicationTask.SendIncompleteNotification and save this into the database. Later on, the code will read the string and dynamically create the task and pass it into another to execute.

Glynis answered 23/3, 2009 at 6:41 Comment(2)
related: #580463 #302309Lillielilliputian
possible duplicate of Get method name and type using lambda expressionLillielilliputian
W
9

The result of ClassName.IntProperty is just an integer value. As soon as it's executed and the result is returned, there's no trace of it having come from IntProperty.

If you're using .NET 3.5 you can use an expression tree instead, usually created via a lambda expression:

Expression<Func<int>> exp = () => ClassName.IntProperty;

You can then compile and execute the expression and separately find out what it's doing (retrieving IntProperty in this case). I'm not really sure whether this is suitable for what you want to do though.

If you do work out how to save the property name in the database, then GetProperty is the way to go on the retrieval front.

Perhaps if you could give more context in the question in terms of how you want to use this, we could help more. You've shown just an expression - if you could show it in terms of where you'd be using it, that would be great.

EDIT: You've expanded the property, but not how it's being called. Do you need to call it directly, rather than just fetching the list of properties using Type.GetProperties and storing the list of property names in the database?

Again, if you could show the code which calls the property, and how you want it to interact with the database, we may be able to make more progress.

Wonderstricken answered 23/3, 2009 at 7:6 Comment(1)
See also the discussion here (and other places): #672468Asiatic
M
74

With C#6.0 you can get it by

nameof(ClassName.IntProperty)
Metzgar answered 14/10, 2016 at 5:38 Comment(2)
This is what I was looking for. Seems the only sane way to selectively bind to a specific property on a class that implements INotifyPropertyChangedDoubleminded
This just made a lot of my code so much easier to refactor! I have a ListCollectionView in my view model and the only way to setup some of the sorting and such is string version of the property name. GamesView.SortDescriptions.Add(new SortDescription(nameof(Game.IsFavorited), ListSortDirection.Descending));Keeshakeeshond
C
34

I think that the use of the GetProperty method in this case, is redundant, because you need to know the property name to call the method.

You could loop through your properties and extract its name:

foreach (PropertyInfo p in typeof(ClassName).GetProperties())
{
    string propertyName = p.Name;
    //....
}
Cohla answered 23/3, 2009 at 7:0 Comment(0)
W
9

The result of ClassName.IntProperty is just an integer value. As soon as it's executed and the result is returned, there's no trace of it having come from IntProperty.

If you're using .NET 3.5 you can use an expression tree instead, usually created via a lambda expression:

Expression<Func<int>> exp = () => ClassName.IntProperty;

You can then compile and execute the expression and separately find out what it's doing (retrieving IntProperty in this case). I'm not really sure whether this is suitable for what you want to do though.

If you do work out how to save the property name in the database, then GetProperty is the way to go on the retrieval front.

Perhaps if you could give more context in the question in terms of how you want to use this, we could help more. You've shown just an expression - if you could show it in terms of where you'd be using it, that would be great.

EDIT: You've expanded the property, but not how it's being called. Do you need to call it directly, rather than just fetching the list of properties using Type.GetProperties and storing the list of property names in the database?

Again, if you could show the code which calls the property, and how you want it to interact with the database, we may be able to make more progress.

Wonderstricken answered 23/3, 2009 at 7:6 Comment(1)
See also the discussion here (and other places): #672468Asiatic
D
4
Type objectType = this.GetType();
PropertyInfo property = objectType.GetProperty("intProperty");
System.Console.Write(property.Name);

Is this what you need?

Decane answered 23/3, 2009 at 6:54 Comment(3)
sorry it's not what i wanted. i've edited the post to make it more clear.Glynis
What if you decide to change the name of "intProperty"? You would have to remember to change this, too. Imho it's bad practice to spread those magic strings around in your codebase. I'd highly recommend to use something like nameof(ClassName.IntProperty) as wintersolider pointed out.Selfsufficient
to get property name we are using the property name string :). c# 6 you can use nameof(class.property). if you rename property somewere else then you will surely get compilation errors for nameofWitless
S
0

You can simply use nameof(ClassName.IntProperty) It will give you "IntProperty"

Sabaean answered 5/7, 2021 at 14:58 Comment(0)
P
-5

I came across this, and it seems very helpful for getting property name. (C++)

#define getVarName(varName,holder) sprintf(holder, "%s", #varName)

int main() {
    int var = 100; // just any type of identifier
    char name[100]; // it will get the variables name
    getVarName(var, name);
    puts(name);
    return 0;
}

ref: http://zobayer.blogspot.com/2010/05/c-fun-get-variables-name.html

Plural answered 30/5, 2011 at 15:21 Comment(1)
The question explicitly mentioned c#. I suggest you post a code conversion as C++ may not be able to convert to c# easily.Kirchner

© 2022 - 2024 — McMap. All rights reserved.