1

Background:

I am creating a COM library and would like to use a modified version of code from this answer. I would like to pass an object to WhatsMyName COM function and return a string representation. I am not entirely sure this is yet possible but trying doesn't hurt ;)

This is how I am seeing it:

Dim myComInst as new MyComLib
MsgBox myComInst.WhatsMyName(myComInst)

and expecting myComInst to be returned.


I am stuck at wrapping the below function so it doesn't take an expression but an object parameter.

public static class MemberInfoGetting
{
    public static string GetMemberName<T>(Expression<Func<T>> memberExpression)
    {
        MemberExpression expressionBody = (MemberExpression)memberExpression.Body;
        return expressionBody.Member.Name;
    }
}

And I can use it like this

string testVariable = "value";
string nameOfTestVariable = MemberInfoGetting.GetMemberName(() => testVariable);

which is rather straight forward.

What I am trying to do is to create a wrapper around it so I can pass any object instead of using the lambda expression in the parameter.

So instead of () => testVariable I'd like to pass just any object.

I have tried to wrap it like this

public string WhatsMyName(object objInstance)
{
    return MemberInfoGetting.GetMemberName(() => objInstance);        
}

but it returns objInstance instead of the object I am passing to the function.

I have tried to use (forgive me) a ref keyword but it doesn't work with lambda expressions.

If any one can first verify whether what I am trying is possible or not that would be great! If it is, then please guide me or point to references about writing a wrapper function for a lambda expression.

You time and help highly appreciated!

Community
  • 1
  • 1

1 Answers1

4

If you pass in the actual expression, rather than an Expression object that represents it, then the expression is being evaluated to its value before it is passed to the function. By the time you're inside the function it is too late to access that information. Using an Expression is passing all of the information used to represent that expression, rather than just its value, which is why you can access it from inside of that function.

Servy
  • 202,030
  • 26
  • 332
  • 449