How to get class and property names and values from undeclared type
Asked Answered
C

2

1

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")
Calmative answered 5/3, 2013 at 18:59 Comment(8)
What do you plan to do with that information?Unchain
Really stupid stuff - generating strings to execute as SQL to update a database. The classes reflect table names and the columns within those tables, so knowing the three bits of information mentioned will help with initialization since it can give me the table name, column name, and value to update when i'm dynamically generating my SQL code. The alternative is manually passing/initializing the values every time, which would be a pain.Calmative
How about using Entity Framework instead of writing your own? Or at least use LINQ to SQL.Unchain
I'm doing it with javascript/ajax - just initializing the data on pageload.Calmative
Sounds like a serious mistake. Using Entity Framework will be much easier and cheaper to maintain. Microsoft has already invented this particular wheel.Unchain
I agree. Unfortunately, EF is not an option.Calmative
Same with LINQ to SQL? Can you say why it's not an option?Unchain
I already am using linq to sql in my project, but this is for client side functionality that I'm creating that's updating fields in an unconventional way which is why I need the information in the OP. I really just need an answer to the OP.Calmative
I
2

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:

// the type being evaluated
public class Foo
{
    public string Bar {
        get;
        set;
    }
}

// method in an evaluator class
public TProperty EvaluateProperty<TProperty>( Expression<Func<Foo, TProperty>> expression ) {
    string propertyToGetName = ( (MemberExpression)expression.Body ).Member.Name;

    // do something with the property name

    // and/or evaluate the expression and get the value of the property
    return expression.Compile()( null );
}

You call it like this (note the expressions being passed):

var foo = new Foo { Bar = "baz" };
string val = EvaluateProperty( o => foo.Bar );

foo = new Foo { Bar = "123456" };
val = EvaluateProperty( o => foo.Bar );
Intern answered 5/3, 2013 at 19:18 Comment(0)
D
1

In this example you need to pass object to InitMethod not property of that object, maybe it will be OK.

class Program
{
    static void Main(string[] args)
    {
        InitMethod(new A() { Id = 100 });
        InitMethod(new B() { Name = "Test Name" });

        Console.ReadLine();
    }

    public static void InitMethod(object obj)
    {
        if (obj != null)
        {
            Console.WriteLine("Class {0}", obj.GetType().Name);
            foreach (var p in obj.GetType().GetProperties())
            {
                Console.WriteLine("Property {0} type {1} value {2}", p.Name, p.GetValue(obj, null).GetType().Name, p.GetValue(obj, null));
            }
        }
    }
}
Dissemble answered 5/3, 2013 at 19:18 Comment(1)
and in this example you can set value of property as well. I done something like this. I have singleton Configuration and in DB i have a table, in table i have KEY => VALUE where KEY is property name (well I have more fields...) and VALUE is value of property. DB is changed by external system but I can sync with that automaticly. If I add property in my code sync will insert new row in db and force external system to set its value... long story.Vanadinite

© 2022 - 2024 — McMap. All rights reserved.