I want to do something like
IsItAStringLiteral(\"yes\")
var v = \"no\";
IsItAStringLiteral(v)
With the obvious return value. Is it possible?
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?
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.