What does '#' at beginning of a variable mean? [duplicate] - c#

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
What does the # symbol before a variable name mean in C#?
I've seen this a couple of times in code that has been passed onto me:
try {
//Do some stuff
}
catch(Exception #exception)
{
//Do catch stuff
}
Can anyone please explain the purpose of the '#' at the beginning of the Exception variable?

It lets you name a variable using a reserved keyword.
For example:
var #class = "something"; // OK
var class = "something"; // Compilation error

Resharper outputs them sometimes if the name of the variable is close to a class name or a namespace i believe, it is just giving it a unique non clashing name

Shameless rip of Michael Meadows answer to a duplicate question follows.
The # symbol allows you to use reserved word. For example:
int #class = 15;
The above works, when the below wouldn't:
int class = 15;

Related

How can I declare a variable with name 'operator'? [duplicate]

This question already has answers here:
What's the use/meaning of the # character in variable names in C#?
(9 answers)
How do I use a C# keyword as a property name?
(1 answer)
C# keywords as a variable
(4 answers)
Closed 3 years ago.
How can I declare a variable with name "operator"?
public string operator;
you can use any reserved word by prefixing the name of your identifier with an # : #operator
var #operator = "+";
var #event = new { name = "Burning man" };
var #var = 23;
var #enum = new List { 1, 2, 3 };
needless to say, this is not so much helping readability, but if you feel it fits your case, you can use it.
Use public string #operator.
The # prefix allows you to use reserved words as variable names.

C# Selecting part of string when there is a matching result in part of the string [duplicate]

This question already has answers here:
Get URL parameters from a string in .NET
(17 answers)
Closed 5 years ago.
I have a string which basically looks like this:
/giveaway/host/setup/ref=aga_h_su_dp?_encoding=UTF8&value_id=1484778065
The trick here is that the length of the string can vary and will change... However the part with "value_id=something" always stays same... So the problem that I ran in was that I can do something like this:
var myId = string.SubString(30,45);
to get the value after value_id= /*this one here*/
I'm thinking that this can be solved by regex or some other way, but I'm not too sure how to write such one. Can someone help me out?
Could you try this. If your value_id always the last of your string you can use this.
var str = "/giveaway/host/setup/ref=aga_h_su_dp?_encoding=UTF8&value_id=1484778065";
var valueId = str.Split('=').LastOrDefault();
Result : 1484778065
Hope it's help to you
You can split by 'value_id='
string[] tokens = str.Split(new[] { "value_id=" }, StringSplitOptions.None);
if(tokens.Length>1){
//parse tokens[1] with the value
}

Invalid string in C# [duplicate]

This question already has answers here:
What's the # in front of a string in C#?
(9 answers)
Closed 7 years ago.
How come this string is valid to open with VLC via a Process:
string fileToPlay = #"C:\Videos\Movies\Movie title.avi";
But this one isn't:
string fileToPlay = #myMovie;
Where the value of the variable myMovie is
"C:\Videos\Movies\Movie title.avi"
Process.Start(vlcPath, fileToPlay );
The problem is that you can only use the # character when placed against string literals like this:
string path = #"c:\temp";
It can be used when placed against a string variable, as you have done, but it has a different meaning. In that case, it is used when you choose an identifier which matches a C# keyword, like this:
string #class = "hello";
You can read more about it here: https://msdn.microsoft.com/en-us/library/aa691090%28v=vs.71%29.aspx

How to preserve "{0}" after two string.Format calls [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
how to add { in String Format c#
When i'm rewriting always the same thing, i'm used to write what I call a string pattern of it.
Let's say I would like to do SQL injection to extend ORM functionality...
protected static string FULLTEXTPATTERN = "EXISTS CONTAINSTABLE([{0}],*,'\"{1}\"') WHERE [key] = {0}.id;
And usually I got the table name and value that i combine in a string.format(FULLTEXTPATTERN ,...) and everything is fine.
Imagine now, I have to do that in two time. first injecting the table name, then the value I search for. So I would like to write something like:
protected static string FULLTEXTPATTERN = "EXISTS CONTAINSTABLE([{0}],*,'\"{{0}}/*Something that returns {0} after string.format*/\"') WHERE [key] = {0}.id;
...
var PartialPattern= string.fomat(FULLTEXTPATTERN, "TableX");
//PartialPattern = "EXISTS CONTAINSTABLE([TableX],*,'\"{0}\"') WHERE [key] = {0}.id"
...
//later in the code
...
var sqlStatement = string.format(PartialPattern,"Pitming");
//sqlStatement = "EXISTS CONTAINSTABLE([TableX],*,'\"Pitming\"') WHERE [key] = {0}.id"
Is there a way to do it ?
Logic says that you would simply put {{{0}}} in the format string to have it reduce down to {0} after the second string.Format call, but you can't - that throws a FormatException. But that's because you need yet another { and }, otherwise it really is not in the correct format :).
What you could do - set your full format to this (note the 4 { and } characters at the end):
"EXISTS CONTAINSTABLE([{0}],*,'\"{{0}}\"') WHERE [key] = {{{{0}}}}.id";
Then your final string will contain the {0} you expect.
As a proof - run this test:
[TestMethod]
public void StringFormatTest()
{
string result = string.Format(string.Format(
"{0} {{0}} {{{{0}}}}", "inner"), "middle");
Assert.AreEqual("inner middle {0}", result);
}
Is it possible to delay generating SQL to the point at which you have all the required inputs so that you can use one call to String.Format() and multiple fields?
Alternatively, you could you build the query iteratively using a StringBuilder rather than String.Format().

C# get string name's name [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to get variable name using reflection?
How to get the string name's name not the value of the string
string MyString = "";
Response.Write(MyString.GetType().Name);//Couldn't get the string name not the value of the string
The result should display back the string name "MyString"
I've found some suggested codes and rewrite it to make it shorter but still didn't like it much.
static string VariableName<T>(T item) where T : class
{
return typeof(T).GetProperties()[0].Name;
}
Response.Write(VariableName(new { MyString }));
I am looking another way to make it shorter like below but didn't how to use convert the current class so i can use them in the same line
Response.Write( typeof(new { MyString }).GetProperties()[0].Name);
While Marcelo's answer (and the linked to "duplicate" question) will explain how to do what you're after, a quick explanation why your code doesn't work.
GetType() does exactly what it says: it gets the Type of the object on which it is called. In your case, it will return System.String, which is the Type of the object referenced by your variable MyString. Thus your code will actually print the .Name of that Type, and not the name of the variable (which is what you actually want.)

Categories