Reputation: 5884
public void Test ()
{
string myString = "hello";
}
public void Method (string text)
{
COnsole.WriteLine ( ... + " : " + text ); // should print "myString : hello"
}
Is it possible to get name of variable passed to a method?
I want to achieve this:
Ensure.NotNull (instnce); // should throw: throw new ArgumentNullException ("instance");
Is it possible? WIth caller info or something similiar?
Without nameof operator?
Upvotes: 2
Views: 1770
Reputation: 48686
Problem with reflection is that, once the C# code is compiled, it will no longer have the variable names. The only way to do this is to promote the variable to a closure, however, you wouldn't be able to call it from a function like you are doing because it would output the new variable name in your function. This would work:
using System;
using System.Linq.Expressions;
public class Program
{
public static void Main()
{
string myString = "My Hello string variable";
// Prints "myString : My Hello String Variable
Console.WriteLine("{0} : {1}", GetVariableName(() => myString), myString);
}
public static string GetVariableName<T>(Expression<Func<T>> expr)
{
var body = (MemberExpression)expr.Body;
return body.Member.Name;
}
}
This would NOT work though:
using System;
using System.Linq.Expressions;
public class Program
{
public static void Main()
{
string myString = "test";
// This will print "myVar : test"
Method(myString);
}
public static void Method(string myVar)
{
Console.WriteLine("{0} : {1}", GetVariableName(() => myVar), myVar);
}
public static string GetVariableName<T>(Expression<Func<T>> expr)
{
var body = (MemberExpression)expr.Body;
return body.Member.Name;
}
}
Upvotes: 4