By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,236 Members | 2,076 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,236 IT Pros & Developers. It's quick & easy.

get name of variable as string?

P: n/a
Shot in the dark, since I know C# doesn't have macros, and thus can't
have a stringizer operator, but I know that you can get the name of
enums as strings, so maybe you can do the same with an ordinary
variable (like an int) somehow. Is it possible? int.ToString()
returns the value of the int as a string, not the name, so I am
thinking 'no'.

Zytan

Mar 30 '07 #1
Share this Question
Share on Google+
45 Replies


P: n/a
"Zytan" <zy**********@gmail.comwrote in message
news:11**********************@d57g2000hsg.googlegr oups.com...
Shot in the dark, since I know C# doesn't have macros, and thus can't
have a stringizer operator, but I know that you can get the name of
enums as strings, so maybe you can do the same with an ordinary
variable (like an int) somehow. Is it possible? int.ToString()
returns the value of the int as a string, not the name, so I am
thinking 'no'.
What are you attempting to do that you need this behavior?
Mar 30 '07 #2

P: n/a
What you want to do is called Reflection. Google "C# Reflection". Also take
a look at the System.Reflection namespace.

"Zytan" wrote:
Shot in the dark, since I know C# doesn't have macros, and thus can't
have a stringizer operator, but I know that you can get the name of
enums as strings, so maybe you can do the same with an ordinary
variable (like an int) somehow. Is it possible? int.ToString()
returns the value of the int as a string, not the name, so I am
thinking 'no'.

Zytan

Mar 30 '07 #3

P: n/a
MBR

"Bill Butler" <qw****@asdf.comwrote in message
news:xdZOh.112519$fo5.27979@trnddc07...
"Zytan" <zy**********@gmail.comwrote in message
news:11**********************@d57g2000hsg.googlegr oups.com...
>Shot in the dark, since I know C# doesn't have macros, and thus can't
have a stringizer operator, but I know that you can get the name of
enums as strings, so maybe you can do the same with an ordinary
variable (like an int) somehow. Is it possible? int.ToString()
returns the value of the int as a string, not the name, so I am
thinking 'no'.

What are you attempting to do that you need this behavior?
There seem to be several postings a week here ostensibly about reflection,
when ordinary non-meta-level techniques are perfectly suitable.
It may not be the case here, but I blame Perl for all this name vs. named
confusion... (Always good to have something to blame :))


--
Posted via a free Usenet account from http://www.teranews.com

Mar 30 '07 #4

P: n/a
Zytan wrote:
Shot in the dark, since I know C# doesn't have macros, and thus can't
have a stringizer operator, but I know that you can get the name of
enums as strings, so maybe you can do the same with an ordinary
variable (like an int) somehow. Is it possible? int.ToString()
returns the value of the int as a string, not the name, so I am
thinking 'no'.
To my best knowledge C# does not have anything
similar to macro and stringifier operator.

What you can get for enums is the string representation
of the value not of the variable name.

Arne
Mar 30 '07 #5

P: n/a
This isn't correct. There is a one-to-many relationship between a class
and the variables that can have a reference to it. That being said, you
can't figure out all the references (the CLR knows, but that info isn't
exposed to you) that are held on any class (or in any variable).
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"rmacias" <rm*****@newsgroup.nospamwrote in message
news:98**********************************@microsof t.com...
What you want to do is called Reflection. Google "C# Reflection". Also
take
a look at the System.Reflection namespace.

"Zytan" wrote:
>Shot in the dark, since I know C# doesn't have macros, and thus can't
have a stringizer operator, but I know that you can get the name of
enums as strings, so maybe you can do the same with an ordinary
variable (like an int) somehow. Is it possible? int.ToString()
returns the value of the int as a string, not the name, so I am
thinking 'no'.

Zytan


Mar 30 '07 #6

P: n/a
Zytan wrote:
Shot in the dark, since I know C# doesn't have macros, and thus can't
have a stringizer operator, but I know that you can get the name of
enums as strings, so maybe you can do the same with an ordinary
variable (like an int) somehow. Is it possible? int.ToString()
returns the value of the int as a string, not the name, so I am
thinking 'no'.

Zytan
I suppose that it might be possible to use reflection to get the name,
but why? What are you planning to use it for?

--
Göran Andersson
_____
http://www.guffa.com
Mar 30 '07 #7

P: n/a
On 29 Mar 2007 17:49:45 -0700, "Zytan" <zy**********@gmail.comwrote:
>Shot in the dark, since I know C# doesn't have macros, and thus can't
have a stringizer operator, but I know that you can get the name of
enums as strings, so maybe you can do the same with an ordinary
variable (like an int) somehow. Is it possible? int.ToString()
returns the value of the int as a string, not the name, so I am
thinking 'no'.

Zytan
In general, no, see Nicholas' response.

A few further points:

1. It is possible to figure out the name of the fields in a type using
Reflection by calling the Type.GetFields() method. That's because
these names form a part of the assembly's metadata. That's very
different from figuring out the name of an instance of the type though
- indeed an instance may not even have a name, it might be living as
an element in a dictionary for example.

2. It is not possible to figure out the name of a local variable
because their names are not compiled into the assembly's metadata.
However, both Reflector and ILDASM *can* get the names of local
variables if the PDB file is available. (Don't even go there, you
don't want to do this!)

--
Philip Daniels
Mar 30 '07 #8

P: n/a
What are you attempting to do that you need this behavior?

Two things:

1. I want a function like Write(i) which will contstruct the string "i
= 45.", where 45 is the value that i is. This is for debugging, and
saves typing WriteLine("i = "+i); With macros and a stringizing
operator, this can be easily, but C# does not support this.

2. I want to get the name of a class. Again for debugging. I have a
WriteLine method that will state who called it by going up the call
stack: caller -writeline. But, I have wrappers for this WriteLine
method, again to save typing (this is debugging, remember, so I like
to speed things up), and this wrapper exists between the caller and
the ending function: caller -wrapper -writeline. So, you can see
that I have to know how far back up the callstack to go. If I had the
class name, I could go until I am out of the class, and get 'caller'
every time.

Zytan

Mar 30 '07 #9

P: n/a
To my best knowledge C# does not have anything
similar to macro and stringifier operator.
No, it doesn't, as I stated, I know this. But, I thought maybe
there's another way.
What you can get for enums is the string representation
of the value not of the variable name.
I meant that it returns a string that is equivalent to what you type
in code. I didn't mean to imply it returns the hidden integer that
exists inside (that you don't have access to unless you explicitly
type cast it). Thus, the value returned is exactly the 'value' you
must type in code (not the hidden value that, for the most part, you
shouldn't ever see or use). This is precisely what I want for a
variable of type int. I want "i" from a variable "int i;", just as I
get "Google" from "MyEnum.Google"

Zytan

Mar 30 '07 #10

P: n/a
This isn't correct. There is a one-to-many relationship between a class
and the variables that can have a reference to it. That being said, you
can't figure out all the references (the CLR knows, but that info isn't
exposed to you) that are held on any class (or in any variable).
What isn't correct? Sorry, Nicholas, I don't follow you at all. I am
not looking for references, or multiple references, and I don't care
about any of the internals. I just want to get a string "i" if my
variable is named "i", regardless of what class or function or inner
loop it is declared in. I know it's probably impossible. Like I
said, just a shot in the dark, just in case.

Zytan

Mar 30 '07 #11

P: n/a
I suppose that it might be possible to use reflection to get the name,
but why? What are you planning to use it for?
Ah, reflection, I know so little about this. I want it for debugging
purposes, to quickly write out a variable and its value, instead of
labouriously typing in WriteLine("i = "+i); each time. Please see
more detailed answer to your question in an another reply.

Zytan

Mar 30 '07 #12

P: n/a
In general, no, see Nicholas' response.

Thought so.
A few further points:

1. It is possible to figure out the name of the fields in a type using
Reflection by calling the Type.GetFields() method. That's because
these names form a part of the assembly's metadata. That's very
different from figuring out the name of an instance of the type though
- indeed an instance may not even have a name, it might be living as
an element in a dictionary for example.
Right. And I want information on the instance. I don't even really
care about the type itself (as long as it supports ToString(), which
all types do).
2. It is not possible to figure out the name of a local variable
because their names are not compiled into the assembly's metadata.
Ok.
However, both Reflector and ILDASM *can* get the names of local
variables if the PDB file is available. (Don't even go there, you
don't want to do this!)
Well, it's just for debugging, so I may want to go there. It's
nothing that'll exist in production code. But, I think you're warning
me that this is a seriously complex solution to a simple matter.
However, if I solved it, I could throw it into a black box and lock it
and never open it again.

Thanks for your reply,

Zytan

Mar 30 '07 #13

P: n/a
2. I want to get the name of a class.

this.Name works for instance classes. I need it for a static class.

Zytan

Mar 30 '07 #14

P: n/a
2. I want to get the name of a class.
>
this.Name works for instance classes. I need it for a static class.
Solution:

System.Diagnostics.StackTrace callStack = new
System.Diagnostics.StackTrace();
System.Diagnostics.StackFrame frame = callStack.GetFrame(0);
System.Reflection.MethodBase method = frame.GetMethod();
string name = method.DeclaringType.Name;

Zytan

Mar 30 '07 #15

P: n/a
Zytan,

Assume you had a class, MyClass, and this:

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

DoSomething(a);

In DoSomething, you have the reference to a, but you can't really unwind
back to a, since a or b both point to it. The logic doesn't make sense.
Also, what do you do when you pass in "new MyClass()", there is no variable
there to work back to. What do you do in that case?
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com
"Zytan" <zy**********@gmail.comwrote in message
news:11**********************@n76g2000hsh.googlegr oups.com...
> This isn't correct. There is a one-to-many relationship between a
class
and the variables that can have a reference to it. That being said, you
can't figure out all the references (the CLR knows, but that info isn't
exposed to you) that are held on any class (or in any variable).

What isn't correct? Sorry, Nicholas, I don't follow you at all. I am
not looking for references, or multiple references, and I don't care
about any of the internals. I just want to get a string "i" if my
variable is named "i", regardless of what class or function or inner
loop it is declared in. I know it's probably impossible. Like I
said, just a shot in the dark, just in case.

Zytan

Mar 30 '07 #16

P: n/a
MyClass a = new MyClass();
MyClass b = a;

DoSomething(a);

In DoSomething, you have the reference to a, but you can't really unwind
back to a, since a or b both point to it. The logic doesn't make sense.
Also, what do you do when you pass in "new MyClass()", there is no variable
there to work back to. What do you do in that case?
Well, in this case, let's say it was defined like so:

void DoSomething(MyClass x)
{
WriteValue(x);
}

I'd want it to write "x = ...", where ... = x.ToString(). So, I'd
want the string "x", not "a" or "b".

I guess even in this case the WriteValue() function needs to go back
one to get the value of x within its caller, DoSomething. It's within
this and each other function that you must acquire the name of its
variables, not within WriteValue(), since it's already lost by then.
This is where macros are needed, so you can inject the same code in
multiple places by write it only once. So, I think this is
unsolvable, due to lack of macros. Even if we were dealing with value
types, the same holds true.

Zytan

Mar 30 '07 #17

P: n/a
Zytan wrote:
>I suppose that it might be possible to use reflection to get the name,
but why? What are you planning to use it for?

Ah, reflection, I know so little about this. I want it for debugging
purposes, to quickly write out a variable and its value, instead of
labouriously typing in WriteLine("i = "+i); each time. Please see
more detailed answer to your question in an another reply.

Zytan
But using reflection to get the name will be very much more typing than
just typing the name.

As you want the name of a local variable, you can't put the code in a
method, as calling a method with the variable as argument would only
send the value of the variable, not the variable itself.

--
Göran Andersson
_____
http://www.guffa.com
Mar 31 '07 #18

P: n/a
But using reflection to get the name will be very much more typing than
just typing the name.

As you want the name of a local variable, you can't put the code in a
method, as calling a method with the variable as argument would only
send the value of the variable, not the variable itself.
Yup, I've come to that conlcusion in another post. This is where
macros are needed -- to insert large amounts of code in lots of
places, but to only have ONE copy of this code, AND to let you only
type very little code in each location to make use of it. It cannot
be done without macros. It's too bad C# didn't have just a little
support for them.

Zytan

Mar 31 '07 #19

P: n/a
Zytan wrote:
>But using reflection to get the name will be very much more typing than
just typing the name.

As you want the name of a local variable, you can't put the code in a
method, as calling a method with the variable as argument would only
send the value of the variable, not the variable itself.

Yup, I've come to that conlcusion in another post. This is where
macros are needed -- to insert large amounts of code in lots of
places, but to only have ONE copy of this code, AND to let you only
type very little code in each location to make use of it. It cannot
be done without macros. It's too bad C# didn't have just a little
support for them.

Zytan
Well, this is one of the few cases where macros could actually be useful.

Generally they are not needed at all, so they would mostly be misused if
available. I believe that not including macros in C# was a good design
decision after all.

--
Göran Andersson
_____
http://www.guffa.com
Mar 31 '07 #20

P: n/a
Well, this is one of the few cases where macros could actually be useful.

Yes,
Generally they are not needed at all, so they would mostly be misused if
available. I believe that not including macros in C# was a good design
decision after all.
I understand and agree.

But, it destroys all the great debugging tools we can make with them,
and since debugging is often a useful thing to do, these features
should have been supplemented with something. Everyone debugs, after
all. And the debugger is powerful, so they do 'get it', it's just
that sometimes, it'd be nice to not have to fire up the chainsaw when
a butter knife will do.

I feel l am being scolded with the rest of the class, just beacuse I
was there, even though I wasn't one of the bad kids misbehaving. The
teacher should at least give me a candy.

Zytan

Mar 31 '07 #21

P: n/a
Zytan wrote:
>What you can get for enums is the string representation
of the value not of the variable name.

I meant that it returns a string that is equivalent to what you type
in code. I didn't mean to imply it returns the hidden integer that
exists inside (that you don't have access to unless you explicitly
type cast it). Thus, the value returned is exactly the 'value' you
must type in code (not the hidden value that, for the most part, you
shouldn't ever see or use). This is precisely what I want for a
variable of type int. I want "i" from a variable "int i;", just as I
get "Google" from "MyEnum.Google"
Variable name and variable value are different things.

int and enum behave the same.

int i = 1;
Colour c = Colour.Green;
Console.WriteLine(i);
Console.WriteLine(c);

writes the value of i and c ("1" and "Green") not the names "i" and "c".

Arne
Apr 1 '07 #22

P: n/a
Variable name and variable value are different things.
>
int and enum behave the same.

int i = 1;
Colour c = Colour.Green;
Console.WriteLine(i);
Console.WriteLine(c);

writes the value of i and c ("1" and "Green") not the names "i" and "c".
Yes. I was just trying to explain what I wanted, and it was a very
bad example to use enums, because people were thinking about the
integer that represents the enum, when the actual value (from C#'s
perspective) is 'Color.Green', not something like '45'. And then I
got a little confused trying to explain it.

To make it clear what I wanted, I'll continue your above case with the
following code. This is what I want to type:

WriteValue(i);
WriteValue(c);

And this is the result I want:

i = 1
c = Color.Green

Which is much easier for debugging than the laborious:

WriteLine("i = " + i);
WriteLine("c = " + c);

Zytan

Apr 1 '07 #23

P: n/a
Zytan <zy**********@gmail.comwrote:

<snip>
I feel l am being scolded with the rest of the class, just beacuse I
was there, even though I wasn't one of the bad kids misbehaving. The
teacher should at least give me a candy.
So how would you have designed the language to allow macro support
"only in the cases where it's appropriate"?

There is *so* much code abusing macros out there, it's clearly too much
of a temptation for most developers.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Apr 1 '07 #24

P: n/a
Zytan wrote:
>Variable name and variable value are different things.

int and enum behave the same.

int i = 1;
Colour c = Colour.Green;
Console.WriteLine(i);
Console.WriteLine(c);

writes the value of i and c ("1" and "Green") not the names "i" and "c".

Yes. I was just trying to explain what I wanted, and it was a very
bad example to use enums, because people were thinking about the
integer that represents the enum, when the actual value (from C#'s
perspective) is 'Color.Green', not something like '45'. And then I
got a little confused trying to explain it.

To make it clear what I wanted, I'll continue your above case with the
following code. This is what I want to type:

WriteValue(i);
WriteValue(c);

And this is the result I want:

i = 1
c = Color.Green

Which is much easier for debugging than the laborious:

WriteLine("i = " + i);
WriteLine("c = " + c);
You want the equivalent of:

#define PRINT(z) cout << #z << " = " << (z) << endl;

:-)

But that is not possible in C#. It is only possible in C++ due
to the preprocessor.

Arne

Apr 1 '07 #25

P: n/a
You want the equivalent of:
>
#define PRINT(z) cout << #z << " = " << (z) << endl;

:-)

But that is not possible in C#. It is only possible in C++ due
to the preprocessor.
Precisely! :) But, C# doesn't allow it since macros can mangle code,
which is true. But, I just want them for simple debugging tools like
this. So, i'd be just as happy if C# provided the debugging tools
themselves, instead of the macros. I know the debugger itself is
great, but sometimes you just want something quick, and sometimes many
of these PRINT statements really can help.

Zytan

Apr 1 '07 #26

P: n/a
I feel l am being scolded with the rest of the class, just beacuse I
was there, even though I wasn't one of the bad kids misbehaving. The
teacher should at least give me a candy.

So how would you have designed the language to allow macro support
"only in the cases where it's appropriate"?
Sorry, I meant to imply that C# was correct to not include macros, but
that they could supplement that loss by adding something ELSE that at
least lets us do what we could with proper macro writing. Say, by
giving us __FILE__, __FUNCTION__, and maybe even my cherished
PRINTVALUE macro that automatically shows the function name, the
variable name, the = sign, and the value, so I can quickly see in the
log / console where and what that value is. Maybe I'm along in
wanting something like this. Seems not many people make use of a
logger / console to debug.

Oh, and even if I can not solve this problem, it doesn't mean it
cannot be solved, say, by someone who has had a decade of experience
designing languages.
There is *so* much code abusing macros out there, it's clearly too much
of a temptation for most developers.
I agree.

Zytan

Apr 1 '07 #27

P: n/a
Zytan <zy**********@gmail.comwrote:
I feel l am being scolded with the rest of the class, just beacuse I
was there, even though I wasn't one of the bad kids misbehaving. The
teacher should at least give me a candy.
So how would you have designed the language to allow macro support
"only in the cases where it's appropriate"?

Sorry, I meant to imply that C# was correct to not include macros, but
that they could supplement that loss by adding something ELSE that at
least lets us do what we could with proper macro writing. Say, by
giving us __FILE__, __FUNCTION__, and maybe even my cherished
PRINTVALUE macro that automatically shows the function name, the
variable name, the = sign, and the value, so I can quickly see in the
log / console where and what that value is. Maybe I'm along in
wanting something like this. Seems not many people make use of a
logger / console to debug.
I do - but I've never particularly had the need to use something like
PRINTVALUE. I keep track of which line I'm printing stuff out from,
then I can see which value is meant to be what from that. Or I just do:

Console.WriteLine ("i={0} j={1}", i, j);

I don't spend so much time debugging that doing the above is a
significant effort. I usually feel that if I've got to that stage, my
code probably isn't clear enough to start with, or I haven't got enough
unit tests. (It's not always the case, of course, but it's a good
initial rule of thumnb.)
Oh, and even if I can not solve this problem, it doesn't mean it
cannot be solved, say, by someone who has had a decade of experience
designing languages.
That's true, of course.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Apr 1 '07 #28

P: n/a
Zytan schrieb:
WriteValue(i);
WriteValue(c);

And this is the result I want:

i = 1
c = Color.Green

Which is much easier for debugging than the laborious:

WriteLine("i = " + i);
WriteLine("c = " + c);
I can't see the benefit. What's wrong with the Debug.WriteLine(i, "i") or
Debug.WriteLine(c, "c") statement? With IntelliSense you don't have to write
that much and you have many more options supporting you for debugging.

Lothar
Apr 1 '07 #29

P: n/a
You can get what you want through reflection. Below is the code that
will return you the name of your variable:

class ty
{
public int i = 0;
}
class Program
{
static void Main(string[] args)
{
ty ob = new ty();
Type t = ob.GetType();
MemberInfo[] mi= t.GetMembers();
foreach (MemberInfo m in mi)
{

Console.WriteLine(m.Name);
}
}
}

with regards,
J.V.Ravichandran
- http://www.geocities.com/
jvravichandran
- Or, just search on "J.V.Ravichandran"
at http://www.Google.com

*** Sent via Developersdex http://www.developersdex.com ***
Apr 3 '07 #30

P: n/a
You can get what you want through reflection. Below is the code that
will return you the name of your variable:
Thanks JV, but the problem is that this code works only inline. It
cannot be moved into a function that could be called more easily than
actually typing the variable name manually.

In other words, I want:

int i = 123;
WriteValue(i);

to print the string:

"i = 123"

The easiest way in C# is to do this:

WriteLine("i = "+i);

Even with reflection, there's no way that's easier than the above.
Unfortunately, the only reason I want it would be because it would be
easier than typing "i" (or some other, likely longer, variable name)
twice.

Thanks for your code,

Zytan

Apr 3 '07 #31

P: n/a
Yes, you can. Override the ToString method of the object class like
below:

class ty
{
public int i = 123;
public string ToString()
{
return "i=" + i.ToString();
}
}

static void Main()
{
ty ob=new ty();
Console.WriteLine(ob.ToString());
}

will output "i=123"

with regards,
J.V.Ravichandran
- http://www.geocities.com/
jvravichandran
- Or, just search on "J.V.Ravichandran"
at http://www.Google.com

*** Sent via Developersdex http://www.developersdex.com ***
Apr 4 '07 #32

P: n/a
Ravichandran J.V. <jv************@yahoo.comwrote:
Yes, you can. Override the ToString method of the object class like
below:

class ty
{
public int i = 123;
public string ToString()
{
return "i=" + i.ToString();
}
}

static void Main()
{
ty ob=new ty();
Console.WriteLine(ob.ToString());
}

will output "i=123"
But again, that's not what Zytan wants - he wants to be able to get
"ob=[whatever]" because he's using the "ob" variable in Main.

You just can't do what Zytan wants to be able to do in .NET.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Apr 4 '07 #33

P: n/a
Hm...sorry abt the names of the class, Jon, but below is the first post
of zytan for your reference:

<snip>Is it possible? int.ToString()
returns the value of the int as a string, not the name, so I am thinking
'no'.
</snip>

with regards,
J.V.Ravichandran
- http://www.geocities.com/
jvravichandran
- Or, just search on "J.V.Ravichandran"
at http://www.Google.com

*** Sent via Developersdex http://www.developersdex.com ***
Apr 4 '07 #34

P: n/a
I guess i have supplied two answers that you do not require (as Jon
pointed out), let me try this one.

Er...can you not use the Immediate window and type "i?" in it? I

with regards,
J.V.Ravichandran
- http://www.geocities.com/
jvravichandran
- Or, just search on "J.V.Ravichandran"
at http://www.Google.com

*** Sent via Developersdex http://www.developersdex.com ***
Apr 4 '07 #35

P: n/a
On Apr 4, 8:16 am, Ravichandran J.V. <jvravichand...@yahoo.comwrote:
Hm...sorry abt the names of the class, Jon, but below is the first post
of zytan for your reference:

<snip>Is it possible? int.ToString()
returns the value of the int as a string, not the name, so I am thinking
'no'.
</snip>
Yes, but he doesn't want to have to use a new class everywhere instead
of the real class - that would be more work than just including the
name of the variable in the log line.

Look at the code he wants to write:

<quote>
In other words, I want:

int i = 123;
WriteValue(i);

to print the string:

"i = 123"
</quote>

Note that he wants a variable called "i" which is an *int* - because,
presumably, he wants to use it elsewhere *as* an int. Creating a whole
new object every time you declare a variable, just to store the
variable name, would be crazy.

Everyone else has already concluded that what Zytan wants just isn't
feasible. Yes, we know you can override ToString in your own classes,
but that doesn't solve the problem. That allows you to name *objects*
(if you start including a name variable everywhere), but as soon as
you've got multiple variables referring to the same object, ToString()
won't be able to give you which variable you happen to have used to
called the method.

Jon

Apr 4 '07 #36

P: n/a
(This isn't technically a C# solution, but hopefully it will solve
your problem Zytan.) So you just want this capability to help you
debug values? You might have more luck solving this problem by writing
an extension for your IDE.

Assuming you use Visual Studio, there are two quick solutions....

1. If you use Resharper it comes with a live template ("outv") that
does this for you.

2. You can create a code snippet that does this for you. I've created
an example code snippet that should work for you.

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/
CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<Title>Zytan's Snippet</Title>
<Shortcut>zytan</Shortcut>
<Description>Code snippet to write a variable to Console.Out</
Description>
<Author>Jay Mitchell</Author>
<SnippetTypes>
<SnippetType>Expansion</SnippetType>
</SnippetTypes>
</Header>
<Snippet>
<Declarations>
<Literal>
<ID>EXPR</ID>
<Default></Default>
<ToolTip>Variable</ToolTip>
</Literal>
</Declarations>
<Code Language="csharp"><![CDATA[System.Console.Out.WriteLine("$EXPR
$ = {0}", $selected$ $EXPR$);
$end$]]>
</Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>
Apr 4 '07 #37

P: n/a
I guess i have supplied two answers that you do not require (as Jon
pointed out), let me try this one.

Er...can you not use the Immediate window and type "i?" in it?
Yes, I guess I could. But, I desired such a function for run-time
display.

Zytan

Apr 5 '07 #38

P: n/a
Here you are, Zytan. A complicated and long piece of code for obtaining
a simple value however, it fulfills your requirement. It will print
"i=123" or any variable that you may declare within a class.

I have used an inline class that is compiled on the fly. You may use an
assembly for which i have also included the ReferencedAssemblies() call
for your reference.

You will need to compile the below code with
"csc /r:base.dll source.cs"

The base.dll can be a simple class with a constructor.

You may also want to create a small assembly and replace the hard-coded
path (c:\c#_prgs\base.dll) in the code when you compile the below
program:

using Microsoft.CSharp;
using System.CodeDom.Compiler;
using System.Windows.Forms;
using System;
using System.Reflection;
public class t
{
static void Main(){
Base myobj;
CSharpCodeProvider csp= new CSharpCodeProvider();
ICodeCompiler ic = csp.CreateCompiler();
CompilerParameters cparam= new CompilerParameters();
cparam.GenerateInMemory = true;
cparam.GenerateExecutable = false;
cparam.ReferencedAssemblies.Add("system.dll");
cparam.ReferencedAssemblies.Add(@"c:\c#_prgs\base. dll");
string str = "using System;"+
"class myclass:Base" +
"{"+
"public myclass(){i=123;}"+
"public int i;"+
"public string ToString()"+
"{"+
"return i.ToString();"+
"}" +
"}";
CompilerResults cres= ic.CompileAssemblyFromSource(cparam,str);
foreach (CompilerError ce in cres.Errors)
MessageBox.Show(ce.ErrorText);

if (cres.Errors.Count == 0 && cres.CompiledAssembly != null)
{
Type ObjType = cres.CompiledAssembly.GetType("myclass");
try
{
if (ObjType != null)
{
myobj = (Base)Activator.CreateInstance(ObjType);
Console.WriteLine(myobj.ToString());
FieldInfo[] f= ObjType.GetFields();
foreach(FieldInfo ff in f)
{
MessageBox.Show(ff.Name + "=" +

ff.GetValue(myobj).ToString());
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}

with regards,
J.V.Ravichandran
- http://www.geocities.com/
jvravichandran
- Or, just search on "J.V.Ravichandran"
at http://www.Google.com

*** Sent via Developersdex http://www.developersdex.com ***
Apr 5 '07 #39

P: n/a
On Apr 5, 8:47 am, Ravichandran J.V. <jvravichand...@yahoo.comwrote:
Here you are, Zytan. A complicated and long piece of code for obtaining
a simple value however, it fulfills your requirement. It will print
"i=123" or any variable that you may declare within a class.
Can you show how it would be *used* though, bearing in mind Zytan's
preferred use case, e.g.:

int i = 45; // Must be int, not some other class, otherwise it's too
intrusive
SomeMethod (i); // Should print out "i=45"

I don't believe that your code will help him to do this - I don't
believe it's *possible* to help him to do this.

Jon

Apr 5 '07 #40

P: n/a
Here you are, Zytan. A complicated and long piece of code for obtaining
a simple value however, it fulfills your requirement. It will print
"i=123" or any variable that you may declare within a class.
J.V.Ravichandran, thanks for your amazing attempt, but, as Jon said,
can you show how it works, before I attempt all of that only to find
it doesn't do what I want? Basically, does it allow this:

int x = 5;
WriteInt(x);

And print the string "x = 5" ?

If so, I could make WriteFloat(), WriteBool(), etc., to allow for
others, that can easily be typed for a quick debugging session. One
function need not handle all types, since I can just make multiple
functions. The purpose is quick typing, and the result is an
unambigious string written out that says just what is going on.

I already have something that prints the method that calls the
function:

class MyClass
{
void MyFunc()
{
int i = 5;
WriteValue("i = "+i);
}
}

will print the string "MyClass.MyFunc(): i = 5"

Zytan

Apr 5 '07 #41

P: n/a
Zytan wrote:
J.V.Ravichandran, thanks for your amazing attempt, but, as Jon said,
can you show how it works, before I attempt all of that only to find
it doesn't do what I want? Basically, does it allow this:

int x = 5;
WriteInt(x);

And print the string "x = 5" ?
I do not think "x" is in the binary code (release).

Arne
Apr 7 '07 #42

P: n/a
Zytan,

Here is the usage.

I m sure you understand that we are doing this exercise only to print a
value at runtime. I m sure you know that the simpler way to do it is as
you have done with a simple writeline call. But, I enjoyed the exercise
so I am giving you the same through reflection.

MyClass ob=new MyClass();
int i=123;
ob.SomeMethod(i);
using System;
using Microsoft.CSharp;
using System.CodeDom.Compiler;
using System.Windows.Forms;
using System.Reflection;
public class MyClass
{
public void SomeMethod(int i)
{
MyClass myobj;
Type t = this.GetType();
myobj = (MyClass)Activator.CreateInstance(t);
MethodInfo[] mi = t.GetMethods();
foreach (MethodInfo m in mi)
{
if (m.Name == "SomeMethod")
{
ParameterInfo[] pi = m.GetParameters();
foreach (ParameterInfo p in pi)
{
Console.WriteLine(p.Name + "=" + i);
}
}
}

}
static void Main()
{
MyClass ob=new MyClass();
int i=123;
ob.SomeMethod(i);
}
}

with regards,
J.V.Ravichandran
- http://www.geocities.com/
jvravichandran
- Or, just search on "J.V.Ravichandran"
at http://www.Google.com

*** Sent via Developersdex http://www.developersdex.com ***
Apr 9 '07 #43

P: n/a
Ravichandran J.V. <jv************@yahoo.comwrote:
Here is the usage.

I m sure you understand that we are doing this exercise only to print a
value at runtime. I m sure you know that the simpler way to do it is as
you have done with a simple writeline call. But, I enjoyed the exercise
so I am giving you the same through reflection.
However, the version you showed prints the *parameter* name, not the
*argument* name. In other words, it's fine in the case of:

public void SomeMethod(int i)
and
int i=123;
ob.SomeMethod(i);

but it would not give the desired output in the case of:

public void SomeMethod(int x)
and
int i=123;
ob.SomeMethod(i);

(It would print x=123 instead of i=123)

It would also print the same value for all the parameters, rather than
the value corresponding to the parameter it's printing out. If you're
hardcoding the "+ i" part of the Console.WriteLine, you might as well
just do: Console.WriteLine ("i=" + i);

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Apr 9 '07 #44

P: n/a
<snip>It would also print the same value for all the parameters, rather
than the value corresponding to the parameter it's printing out. </snip>

Yes. But if this is such an issue, it can be sorted out with an 'if'
condition in the for loop.

Hardcoding the +i is not necessary. It, too, can be reflected upon.
with regards,
J.V.Ravichandran
- http://www.geocities.com/
jvravichandran
- Or, just search on "J.V.Ravichandran"
at http://www.Google.com

*** Sent via Developersdex http://www.developersdex.com ***
Apr 10 '07 #45

P: n/a
Ravichandran J.V. <jv************@yahoo.comwrote:
<snip>It would also print the same value for all the parameters, rather
than the value corresponding to the parameter it's printing out. </snip>

Yes. But if this is such an issue, it can be sorted out with an 'if'
condition in the for loop.
Yes - but it would still be the parameter name rather than the argument
name, contrary to the original intention.
Hardcoding the +i is not necessary. It, too, can be reflected upon.
No, it can't. You can't get the values of local variables/parameters
using reflection.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Apr 10 '07 #46

This discussion thread is closed

Replies have been disabled for this discussion.