Jeff Jeff - 1 year ago 85
C# Question

How to get name of a class property?

Is there anyway I can get the name of class property


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

//something like below but I want to get the string of "IntProperty"

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.



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
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:
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.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download