tags:

views:

70

answers:

6

Possible Duplicate:
print name of the variable in c#

How I can print the name of any object

MyClass c1, c2;

printName(c1);
printName(c2);

void printName(Object o)
{
    Console.WriteLine("name of object : "+ o.???());
}

output should be like this:

name of object : c1
name of object : c2

This is specific to .Net, but answer for other platform/language can be helpful.

A: 

That is not possible.
Name of the variable is of importance only to the developer (not the compiler or runtime).

You could create a Dictionary<string, object> & add those instances with the name of their variable to achieve something like that.

EDIT: And that is the reason, it is said - write code for people to understand and incidentally for the compiler.

shahkalpesh
As always, please explain when downvoting, why?
shahkalpesh
Huh? So I have this `Dictionary<string, object>`. And I have these variables `s` and `t` declared as follows: `string s = "Hello, world!"` and `string t = s`. And I guess I put `("s", "Hello, World!")` and `("t", "Hello, World!")` in this dictionary. And so now I'm in this method `printName` which was called via `printName(s)`. So how do I use this dictionary to find `"s"`? And how do I know I shouldn't be finding `"t"`?
Jason
shahkalpesh
But still what happens if I have `string s = "Hello, world!"` and `string t = s`? I can't have both `("Hello, world!", "s")` and `("Hello, world!", "t")` in the dictionary (duplicate key!) and so if I only have one then `printName` invoked with the other as a parameter will fail. And what happens on `printName("Hello, world!")` It prints `s`? `t`? Or what about `int a = 0, object u = a` and `object v = a`. Now these don't even refer to the same object. Now what happens when I try to lookup still yet another boxed instance of `a`?
Jason
@Jason: Did I say that I don't agree with you on this? I will repeat - I looked at the code OP provided. Please read my comments again. You will see that I have said - You are right :)
shahkalpesh
+1  A: 

The name doesn't exist outside of the source code - to do this, you would have to be attached to yourself as a debugger, or dig through the PDBs. In short, this not practical in any measure for C# and most other languages.

Paul Betts
A: 

This is impossible.

What is the result of this?

string s = "Hello, world!";
string t = s;
printName(t);

As s and t both refer to the same instance of string there is no way to distinguish between invocations of printName with s as the parameter versus t as the parameter.

And what should be the result of this?

printName("Hello, world!");
Jason
@Jason: Please see my reply to your comment above. I hope, I am talking sense :)
shahkalpesh
A: 

I don't think it's theoretically possible. Think about this scenario:

MyClass a, b;
a = new MyClass();
b = a;

Console.WriteLine("name of b is " + SomeMagicClass.GetVarName(b));
//Should it be "b" or "a"?

I am sure there is a better explanation involving generated MIDL code along the lines of variable name not even being present at runtime.

EDIT Alas I was wrong. Inspired by Jon Skeet's post about Null Reference exception handling and suddenly being reminded about projection there is a way to kinda do that.

Here is complete working codez:

public static class ObjectExtensions {
    public static string GetVariableName<T>(this T obj) {
        System.Reflection.PropertyInfo[] objGetTypeGetProperties = obj.GetType().GetProperties();

        if(objGetTypeGetProperties.Length == 1)
            return objGetTypeGetProperties[0].Name;
        else
            throw new ArgumentException("object must contain one property");
    }
}

class Program {
    static void Main(string[] args) {
        string strName = "sdsd";
        Console.WriteLine(new {strName}.GetVariableName());

        int intName = 2343;
        Console.WriteLine(new { intName }.GetVariableName());
    }
}
Igor Zevaka
A: 

That does not make sense for the following reason:

The object itself is in memory and has no name. You are accessing it using a reference which has a name. Thus, the reference name can change in any moment, you can have 50 references "pointing" to the same nameless object, etc.

Consider this:

MyClass c1, c2;
c1 = new MyClass();
c2 = c1;
printName(c1);
printName(c2);

As you can see, both c1 and c2 are references to the exact same object which has no way of "knowing" who is referencing it or by which name.

Seth Illgard
A: 

You need to place a Name property inside your MyClass class, eg.

class MyClass {
  public string Name {get;set;}

  // rest of class goes here
  // ...
}

then you can use it as follows:

var c1 = new MyClass() { Name = "c1" };
var c2 = new MyClass() { Name = "c2" };

printName(c1);
printName(c2);

void printName(MyClass o)
{
    Console.WriteLine("name of object : "+ o.Name);
}
Will
This doesn't work if the object passed to `printName` doesn't have a `Name` property.
Jason
If you read printName correctly, you'll see that it takes in a MyClass object, which is guaranteed to have a name.
Will
Your antecedent is correct but the consequent is wrong. Here: `void printName(Object o)`. Notice also that he says "[h]ow I can print the name of any object[?]".
Jason
Oh, you're talking about your declaration of `printName`? Well then you didn't solve the problem that he was trying to solve (print the name of any object).
Jason
You're correct, this wouldn't work for all object types. I simply offered an option to assist with classes under his control, as his code did use "MyClass", which presumably he could modify. *shrugs*
Will