views:

265

answers:

4

Say I have a class with one property

Public Class MyClass
   Public Property MyItem() as Object
      ....
   End Property
End Class

I have to pass the name of the property to a function call. (Please don't ask why it should be done this way, its a third party framework). For example

SomeFunc("MyItem")

But what I would like to do is, change the string into a strongly typed parameter. Meaning, if the property name is renamed or changed, it should be reflected here too.

So something of this type :

Dim objectForStrongTyping as New MyClass()
SomeFunc(objectForStrongTyping.MyItem().Name())

I am sure this won't work. Is there a way this strong typing can be done? (C# or VB.NET, any thing is cool)

A: 

You could always use a static class that contains string constants instead of passing in a string literal:

public static class ObjectForStrongTyping
{
    public const string MyItem = "MyItem";
    public const string MyOtherItem = "MyOtherItem";
    // ...
}

Your code would then become:

SomeFunc(ObjectForStrongTyping.MyItem);
John Rasch
+1: while its not as "automatic" as the LINQ and typeof(...) solutions, its super simple and maintenance is minimal.
Juliet
A: 

If there is only one property you could do this - get the property info on the first property of the class:

//C# syntax
typeof(MyClass).GetProperties()[0].Name;

'VB syntax
GetType(MyClass).GetProperties()(0).Name

EDIT Turns out, where you can use expressions, you can also use projection for this kind of reflection (C# code).

public static class ObjectExtensions {
    public static string GetVariableName<T>(this T obj) {
        System.Reflection.PropertyInfo[] objGetTypeGetProperties = obj.GetType().GetProperties();

        if(objGetTypeGetProperties.Length == 1)
            return objGetTypeGetProperties[0].Name;
        else
            throw new ArgumentException("object must contain one property");
    }
}

class Program {
    static void Main(string[] args) {
        Console.WriteLine(Console.WriteLine(new { (new MyClass()).MyItem}.GetVariableName()););
    }
}

With this solution, the class can have any number of properties, you would be able to get any other their names.

Igor Zevaka
Ouch. Now instead of being worrying about Properties changing names, we have to worry about adding/reordering Properties?
Greg
Yeah, it's pretty dirty, but as per the OP, the class only has one property. See edit for a better solution.
Igor Zevaka
+6  A: 

Here is a solution using classes from System.Linq.Expressions.

static MemberInfo GetMemberInfo<TObject, TProperty>(
    Expression<Func<TObject, TProperty>> expression
) {
    var member = expression.Body as MemberExpression;
    if (member != null) {
        return member.Member;
    }

    throw new ArgumentException("expression");
}

Just throw this in a class somewhere (ExpressionHelper?).

Usage:

class SomeClass {
    public string SomeProperty { get; set; }
}

MemberInfo member = GetMemberInfo((SomeClass s) => s.SomeProperty);
Console.WriteLine(member.Name); // prints "SomeProperty" on the console
Jason
+1 For great quick-snip!
KMan
Nice, can this be wrapped into an extension?
ChaosPandion
+1  A: 

This solution works in both C# and VB.NET, but the VB.NET syntax for lambda functions is not as clean, which would probably make this solution less attractive in VB. My examples will be in C#.

You can achieve the effect you want using the lambda function and expression tree features of C# 3. Basically, you would write a wrapper function called SomeFuncHelper and call it like this:

MyClass objForStrongTyping = new MyClass();
SomeFuncHelper(() => objForStrongTyping.MyItem);

SomeFuncHelper is implemented as follows:

void SomeFuncHelper(Expression<Func<object>> expression)
{
    string propertyName = /* get name by examining expression */;
    SomeFunc(propertyName);
}

The lambda expression () => objForStrongTyping.MyItem gets translated into an Expression object which is passed to SomeFuncHelper. SomeFuncHelper examines the Expression, pulls out the property name, and calls SomeFunc. In my quick test, the following code works for retrieving the property name, assuming SomeFuncHelper is always called as shown above (i.e. () => someObject.SomeProperty):

propertyName = ((MemberExpression) ((UnaryExpression) expression.Body).Operand).Member.Name;

You'll probably want to read up on expression trees and work with the code to make it more robust, but that's the general idea.

Update: This is similar to Jason's solution, but allows the lambda expression inside the helper-function call to be a bit simpler (() => obj.Property instead of (SomeType obj) => obj.Property). Of course, this is only simpler if you already have an instance of the type sitting around.

Aaron