What is the difference between using single and double quotes in C#?

Asked

Viewed 5,129 times

12

In PHP, when we use single quotes or double quotes, both forms have the functionality to declare a string. There is only one small difference.

I am now starting a study with C#. When I went to try to declare a string with single quotes, an error was generated.

 [Table('ProductSuppliers')]

Too Many characters in Character literal

In PHP there was no problem to use simple quotes in cases like the one shown above.

Since the error is being pointed out, it makes me think that the simple quotes do not have the purpose that I was thinking.

  • What is the purpose of Single Quotes in C#?

  • What’s her difference to Double Quotes?

  • Why did the error described above occur when I tried to use the statement 'ProductSupplier'?

  • 2

    TL;DR;: Single quotes: char. Double quotes: chain of chars (string)

  • This -1 could be explained there. So I could improve the details of the question, since it contains some error

3 answers

13


It is different from PHP where they are almost interchangeable.

Single quotes or apostrophe only serves to delimit a single character (type char - part of a UTF-16).

Double quotes serve to delimit a string, that is, an immutable collection of chars with specific format.

The error rightly indicates that it has more than one character. As it is a text and not just a character just put double quotes.

As strings can be defined with some prefixes to facilitate certain operations:

11

Unlike PHP, in C#, they represent two different types.

Single quotes are used to define a single character (type char).

Double quotes serve to delimit a string (which is an immutable collection of chars).

The error, in your case, occurs because there is more than one character between the simple quotes. What you intend to use there is a string, then just exchange the single quotes for double.

Example:

char meuChar = 'A';
char[] meuCharArray = { 'O', 'L', 'Á' };
string minhaString = "OLÁ";

Some other languages also work this way.

9

Single quotes represent a char, so should be used SOLELY to assign characters. Ex:

char sexo = 'M';

Double quotes represent a string ( a collection of char ). Ex:

string sexo = "masculino";

Note that a String (String, or char array ) may contain only one character, but a char NEVER may contain more than one character. Ex:

string sexo = "M"; // Correto, uma cadeia de caracteres pode conter apenas um caractere.
char sex = 'sexo'; // Erro de compilação, um char não pode conter mais que um caractere.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.