473,387 Members | 1,899 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

get name of variable as string?

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
45 13538
"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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
(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
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
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
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
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
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
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
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
<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
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
by: cpp | last post by:
I am trying to find out how to assign the name of a variable (aka identifier) given a string for this name. For example: string s = "whatever"; How can I obtain the following expression:...
5
by: Matt Clepper | last post by:
Any way to do this? I need to call functions based on a variable. Do I actually have to make a case statement and call each funciton explicitly, or is there any way to call a function where the...
4
by: archmonkey | last post by:
Hello Is there a way to get a pointer to a variable through the variable name represented as a string? Let me explain it through an example: /* Start code example */ int MyVar = 3;
6
by: Raed Sawalha | last post by:
i have the following case a MyClass class has method with 2 arguments as void SetProp(string varname,string varvalue); in MyClass i have following members string...
7
by: RSH | last post by:
This is probably a very simple question but... How do I get the instantiated name of an object from within the class? Example: Sub main Dim c1 as new TestClass() c1.PrintName()
6
by: Adam Atlas | last post by:
Is it possible for an object, in its __init__ method, to find out if it is being assigned to a variable, and if so, what that variable's name is? I can think of some potentially ugly ways of...
6
by: Bora Ji | last post by:
Please help me to creating dynamic VARIABLE in java, with predefined name.
9
by: JohnR | last post by:
I have the name of a control in a string variable and I want to change one of the controls properties. Right now I recursively scan all the controls on the form until I get one whose name matches...
2
by: X l e c t r i c | last post by:
Here: http://bigbangfodder.fileave.com/res/sandr.html I'm trying to use string.replace() for a basic search and replace form using textarea values as the regexp and replacement values for...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.