In the C# variable declaration? Usage of and @

Posted by pourmeanother on Mon, 07 Mar 2022 02:29:02 +0100

1, When defining variables, add "? After the data type

Add "? After variable type Represents a nullable value type.
For example:
int a = null;

The above code VS will prompt an error: null cannot be converted to "int" because it is a non nullable value type.

However, if it is written in the following format, there will be no error:

int? a = null;

At this time, variable a can be null, and its HasValue property can be used to determine whether there is a Value, and the real Value can be obtained through the Value property.

It can be created implicitly by directly assigning a value to the packaging type, such as:

int? a = 5;

Types such as Int32 and struct cannot be empty. Common types such as int and datetime cannot be empty. Therefore, when you need to judge whether there is a value, you can use the nullable value type with a question mark, such as int?,DateTime?

Specifically, you can search "nullable value type" for more information.


2, Usage of @ symbol in C #

1. Everyone on earth knows that the string constant of # in # C # can start with @. This has the advantage that the escape sequence "no" is processed and output "as is", that is, we can easily code the escape character without adding \ (backslash). For example,

string filePath = @"c:\Docs\Source\a.txt"  // rather than "c:\\Docs\\Source\\a.txt"


2. If you want to include a double quotation mark in a string enclosed by @ you need to use two pairs of double quotation marks.
At this time, you can't use \ to escape quotation marks, because the escape purpose of \ here has been @ "blocked". For example,

@"""Ahoy!"" cried the captain."    // The output is: "Ahoy!" cried the captain.

It is a bit like the processing method of single quotation mark constant in SQL:

DECLARE @msg varchar(100)
SET @msg = ''Ahoy!'' cried the captain.'  -- Output is: 'Ahoy!' cried the captain.


3. @ will recognize line breaks
In fact, I don't know how to describe this feature. I just found it by accident. Let's look at the following code first:

string script = @"
            <script type=""type/javascript"">
            function doSomething()
Be at ease here cs Write in file js,The structure is very clear. Normally, we are like this coding Of:
string script2 = 
            "<script type=\"type/javascript\">function doSomething(){}</script>";
// or
string script3 =
            "<script type=\"type/javascript\">" +
            "function doSomething(){ " +

We usually choose the latter, because js code is generally long, or the method body is large, or other variables need to be connected, so the structure is relatively clear.

Note: if there are many "splicing" times, you should consider using StringBuilder to improve performance.

Another scenario, which is also very common, is to splice SQL statements in the program, such as:

private const string SQL_INS_USER = @"
            INSERT INTO t_User([UserName], [Password], Email) 
                        VALUES(@UserName, @Password, @Email)";

Haha, it's like writing stored procedures to maintain high code clarity.

However, we need to pay attention to one problem: string length

Look at the following test code:

private const string SQL_INS_USER1 = @"
            INSERT INTO t_User([UserName], [Password], Email) 
                        VALUES(@UserName, @Password, @Email)";
        private const string SQL_INS_USER2 = @"INSERT INTO t_User([UserName], [Password], Email) 
                        VALUES(@UserName, @Password, @Email)";
        private const string SQL_INS_USER3 = @"INSERT INTO t_User([UserName], [Password], Email) VALUES(@UserName, @Password, @Email)"; 
        static void Main(string[] args)
            Console.WriteLine(SQL_INS_USER1.Length);    //  126 
            Console.WriteLine(SQL_INS_USER2.Length);    //  112
            Console.WriteLine(SQL_INS_USER3.Length);    //  86

You can see that the lengths of the three strings are different, 14 = 126-112 and 26 = 112-86 respectively. Note that in the code editor, SQL_ INS_ After the first newline symbol in user1 , I indent 13 spaces (before INSERT), and
SQL_ INS_ After the first newline symbol in user2 , I indent 25 spaces (before VALUES),
So, add a line feed, just 14 and 26


Writing the code in this way, although it improves the clarity and simplicity of the code, it brings another problem in no line: character length!
In many scenarios, we may hope that the shorter the string, the better. For example, through ADO Net sends SQL statements to the database for execution.
So pay more attention when using!


4. Usage in identifiers

In C # specification, @ can be used as the first character of identifier (class name, variable name, method name, etc.), so as to allow C # to retain keywords as self-defined identifiers.
For example:

class @class
   public static void @static(bool @bool) {
      if (@bool)
class Class1
   static void M() {

Note that although @ appears in the identifier, it is not part of the identifier itself.
Therefore, the above example defines a class named "class" and contains a method named "static" and a formal parameter named "bool".

In this way, it brings convenience to cross language transplantation. Because a word is a reserved keyword in C #, but it may not be in other languages.

See for details

C# Language Specification
2.4.2 Identifiers