Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between double quotes and single quote in C#

Tags:

c#

People also ask

What is the difference between 1 and 2 quotation marks?

If you are an American, using quotation marks could hardly be simpler: Use double quotation marks at all times unless quoting something within a quotation, when you use single. It's different in the greater Anglosphere, where they generally use singles in books and doubles in newspapers.

Why use single quotes instead of double quotes?

The most common reason to use single quotation marks is to quote someone who is quoting someone else. The rules are different in British English, but in American English, you enclose the primary speaker's comments in double quotation marks, and then you enclose the thing they are quoting in single quotation marks.

What is the difference between single and double inverted commas?

Double quotation marks (in British English) are used to indicate direct speech within direct speech (use single inverted commas for direct speech and double quotation marks to enclose quoted material within).


Single quotes encode a single character (data type char), while double quotes encode a string of multiple characters. The difference is similar to the difference between a single integer and an array of integers.

char c = 'c';
string s = "s"; // String containing a single character.
System.Diagnostics.Debug.Assert(s.Length == 1);
char d = s[0];

int i = 42;
int[] a = new int[] { 42 }; // Array containing a single int.
System.Diagnostics.Debug.Assert(a.Length == 1);
int j = a[0];

when you say string s = "this string" then s[0] is a char at at specific index in that string (in this case s[0] == 't')

So to answer your question, use double quotes or single quotes, you can think of the following as meaning the same thing:

string s = " word word";

// check for space as first character using single quotes
if(s[0] == ' ') {
 // do something
}

// check for space using string notation
if(s[0] == " "[0]) {
 // do something
}

As you can see, using a single quote to determine a single char is a lot easier than trying to convert our string into a char just for testing.

if(s[0] == " "[0]) { 
 // do something
}

is really like saying:

string space = " ";
if(s[0] == space[0]) {
 // do something
}

Hopefully I did not confuse you more!


the single quote represent a single character 'A', double quote append a null terminator '\0' to the end of the string literal, " " is actually " \0" which is one byte larger than the intended size.