Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strong Typing a property name in .NET

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)

like image 761
Jey Geethan Avatar asked Dec 31 '09 06:12

Jey Geethan


3 Answers

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
like image 75
jason Avatar answered Oct 02 '22 23:10

jason


In C# 6.0 There is a new feature called nameof. Basically you can do this:

var name = nameof(MyClass.MyItem);

Looking at Telerik code converter from C# to VB it seems this is the VB equivalent:

Dim name = nameof([MyClass].MyItem)

So you can do the following:

SomeFunc(nameof(MyClass.MyItem));

Here is the reference to microsoft documentation: https://docs.microsoft.com/en-us/dotnet/articles/csharp/language-reference/keywords/nameof

like image 35
Marko Avatar answered Oct 03 '22 01:10

Marko


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.

like image 21
Aaron Avatar answered Oct 02 '22 23:10

Aaron