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

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

I coded a program to count how many words are in a file

using System;
using System.IO;
namespace Consoleapp05
{
    class Program
    {
        public static void Main(string[] args)
        {
            StreamReader sr = new StreamReader(@"C:\words.txt");
            string text = sr.ReadToEnd();
            int howmany = 0;
            int howmany2 = 0;

            for(int i = 0; i < text.Length; i++)
            {
                if(text[i] == " ")
                {
                howmany++;
                }
            }
            howmany2 = howmany + 1;
            Console.WriteLine("It is {0} words in the file", howmany2);
            Console.ReadKey(true);
        }
    }
}

This gives me an error because of the double quotes. My teacher told me to use single quote instead, but he didn't tell me why. So what's the difference between double quotes and single quote in C#?


Solution 1:

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];

Solution 2:

When you say string s = "this string" then s[0] is a character at a 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 character is a lot easier than trying to convert our string into a character just for testing.

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

is really like saying:

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

Solution 3:

The single quote represents a single character 'A', and double quote appends a null terminator '\0' to the end of the string literal.

" " is actually " \0" which is one byte larger than the intended size.