using System.Collections.Generic;
using System.Diagnostics;
using System.Linq.Expressions;
public static void Main()
Console.WriteLine("Hello World");
Console.WriteLine(obj1.Name());
Console.WriteLine(obj2.Name());
Console.WriteLine(obj3.Name());
public Dictionary<string, string> nameOfAlreadyAcessed = new Dictionary<string, string>();
public string nameOf(object obj, int level = 1)
StackFrame stackFrame = new StackTrace(true).GetFrame(level);
string fileName = stackFrame.GetFileName();
int lineNumber = stackFrame.GetFileLineNumber();
string uniqueId = fileName + lineNumber;
if (nameOfAlreadyAcessed.ContainsKey(uniqueId))
return nameOfAlreadyAcessed[uniqueId];
System.IO.StreamReader file = new System.IO.StreamReader(fileName);
for (int i = 0; i < lineNumber - 1; i++)
string varName = file.ReadLine().Split(new char[]
nameOfAlreadyAcessed.Add(uniqueId, varName);
public static class ObjectInstanceExtensions
private static Dictionary<object, string> namedInstances = new Dictionary<object, string>();
public static void Named<T>(this T instance, Expression<Func<T>> expressionContainingOnlyYourInstance)
var name = ((MemberExpression)expressionContainingOnlyYourInstance.Body).Member.Name;
public static T Named<T>(this T instance, string named)
if (namedInstances.ContainsKey(instance))
namedInstances[instance] = named;
namedInstances.Add(instance, named);
public static string Name<T>(this T instance)
if (namedInstances.ContainsKey(instance))
return namedInstances[instance];
throw new NotImplementedException("object has not been named");