Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get name of a class property?

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.

like image 845
Jeff Avatar asked Mar 23 '09 06:03

Jeff


People also ask

How can I find the class name of a property?

You could loop through your properties and extract its name: foreach (PropertyInfo p in typeof(ClassName). GetProperties()) { string propertyName = p.Name; //.... }

How do I find the property name and value?

public class myClass { public int a { get; set; } public int b { get; set; } public int c { get; set; } } public void myMethod(myClass data) { Dictionary<string, string> myDict = new Dictionary<string, string>(); Type t = data. GetType(); foreach (PropertyInfo pi in t. GetProperties()) { myDict[pi.Name] = //...

How do you check if property is of type is a class?

Examples. The following example creates an instance of a type and indicates whether the type is a class. type MyDemoClass = class end try let myType = typeof<MyDemoClass> // Get and display the 'IsClass' property of the 'MyDemoClass' instance. printfn $"\nIs the specified type a class? {myType.

What are property names?

Noun. Definition: Identifies the property name that is displayed on the Property List; an easily recognizable or descriptive name; typically a street address or property name (e.g. “100 Main Street” or “Commerce Center Mall'). The default name is the Loan Name.


1 Answers

With C#6.0 you can get it by

nameof(ClassName.IntProperty) 
like image 145
Ajay Bhasy Avatar answered Sep 24 '22 18:09

Ajay Bhasy