-3

When I am tracing, I think it would be useful to do something like

//In the main function
{
  Log(myVariable);
}

Which sends the variable to a generic function like this

//In the Logger file
public static void TraceMessage<T>(T aVariable)
{
   string oldName=GetOldName(aVariable);
}

I want "myVariable" to be assigned to oldName. What should GetOldName do?

Something similar was asked here:

get name of a variable or parameter

But in all of those cases, "aVariable" is assigned to oldName.

Update: Old name is what the parameter/variable was called before it was sent to the function. I use it as a variable here just for ease of explaining. The reason for this is debugging. When my program receives an error I would like to know what the value of my variables are. I currently have to send Log(the error, the variable name, the variable value). When you write 1000 of the these Debug statements you think of ways this could be simplified. What I am asking would simplify the problem.

Why did my question get downvoted and how can I improve the question?

Douglas
  • 53,759
  • 13
  • 140
  • 188
Seth Kitchen
  • 1,526
  • 19
  • 53
  • What do you mean by `oldName` ? – EZI Aug 21 '15 at 19:41
  • 2
    I don't think this is possible. I also don't think it's necessary. Why would you ever need to do this? – David Aug 21 '15 at 19:41
  • 1
    Don't let the downvotes get to you. I've upvoted you since I feel it's a valid question, even if it there doesn't exist a way of achieving what you're requesting. – Douglas Aug 24 '15 at 17:00

1 Answers1

1

This information needs to be captured and provided by the caller. In C# 6, it can be easily achieved using the nameof operator, although you'll need to apply this in your caller code:

Log(myVariable, nameof(myVariable));

Edit: If you only want to specify your variable once, you can use:

Log(() => myVariable);

And define your Log method as:

public static void Log<T>(Expression<Func<T>> expression)
{
    string oldName = ((MemberExpression)expression.Body).Member.Name;
    object value = expression.Compile().Invoke();
}

However, this will be much slower than the alternative, and is not guaranteed behaviour.

Community
  • 1
  • 1
Douglas
  • 53,759
  • 13
  • 140
  • 188
  • The edit is a very good solution, but if there is one without the () =>, it would be better. – Seth Kitchen Aug 21 '15 at 19:57
  • In that case, leave the question open. I'd be curious to see whether one exists. For the record, I personally wouldn't use the lambdas in my code due to the issues I mentioned (speed and lack of spec); I'd prefer to go with `Log(myVariable, nameof(myVariable))`. – Douglas Aug 21 '15 at 20:15