If I have these two classes:
public class A
{
public int Id { get; set; }
}
public class B
{
public string Name { get; set; }
}
Can I use a generic method like this:
public void InitMethod(object classProperty)
To pass in data like this:
var a = new A() { Id = 1 };
var b = new B() { Name = "John" };
InitMethod(a.Id);
InitMethod(b.Name);
And get the following information from within the method:
- Class name (ex: "A", "B")
- Property name (ex: "Id", "Name")
- Property value (ex: 1, "John")
In this example you need to pass object to InitMethod not property of that object, maybe it will be OK.
Sort of, although it may be more trouble than it is worth.
ASP.Net MVC frequently uses expressions to get at property info in a strongly-typed fashion. The expression doesn't necessarily get evaluated; instead, it is parsed for its metadata.
This isn't specific to MVC; I mention it to cite an established pattern in a Microsoft framework.
Here's a sample that gets a property name and value from an expression:
You call it like this (note the expressions being passed):