views:

87

answers:

2

I want to do something like

IsItAStringLiteral("yes")
var v = "no";
IsItAStringLiteral(v)

With the obvious return value. Is it possible?

+2  A: 

You can use the string.IsInterned method to determine whether a given string is in the .NET intern pool. All string literals are automatically added to the intern pool before the application begins running.

Of course, that won't help you with your exact question. Variable 'v' will reference a string literal, so it too will appear in the intern pool. Why do you need such functionality?

MikeP
This works pretty well and does what i want http://www.pastie.org/1225201
acidzombie24
@acidzombie, can you please explain what did you use it for, can be useful to others
Vinay Pandey
@Vinay Pandey: ok sure i added the comment to my question.
acidzombie24
+1  A: 

No. You won't be able to tell whether a string is a literal or not.

The simple reason: Literals, string variables, interned strings of all kinds....each one is a reference to a System.String. And all strings, when passed by value, are loaded onto the stack prior to the function call that uses them (and thus, are unrelated to the name of any variable that references them). By the time the function is called, a literal and a variable look exactly the same, and will be treated exactly the same when passed by value.

The only way that might be possible is some unsafe stuff that might check the address of the object. If the address is within an assembly's address space, it almost certainly came from a constant of some sort. But that's unreliable (as strings set to literals would look just like the literals), extremely hackish, ugly, and above all unnecessary for any purpose that i can think of.

You should probably reconsider how you're doing whatever you're doing, if you have to care whether a string is a literal or not.

cHao