Start learning free

LESSON 5 OF 413 · WELCOME TO C#

Syntax Errors in C#

Lesson

TL ; DR:

  • Syntax errors are mistakes in the use of the C# language, analogous to spelling or grammar mistakes in a language like English. For example:


  • Omitting quotes when working with strings:

    Console.WriteLine("Welcome!);
    

  • Omitting parantheses when using the Console.WriteLine method:

    Console.WriteLine("Let's code!";
    

  • When C# encounters a syntax error, it refuses to compile your code, so nothing runs, and reports a compiler error instead.




Full lesson:

Humans are prone to making mistakes. Humans are also typically in charge of creating computer programs. To compensate, programming languages attempt to understand and explain mistakes made in their programs.

Here are two common errors that we encounter while writing C# code:


The syntax error:

Syntax errors are mistakes in the use of the C# language, and are analogous to spelling or grammar mistakes in a language like English. For example, the sentence "Would you some tea?" does not make sense – it is missing a verb.

Syntax error means there is something wrong with the way your program is written. Some examples:

1. Mismatched quotes when declaring a string:

string greeting = 'Hey there!";

When we run this code we'll get an error CS1010: Newline in constant.

2. Leaving out a parenthesis:

Console.WriteLine"Hey");

When we run this code we'll get an error CS1002: ; expected.


The reference error:

A reference error occurs when the C# compiler sees a word it does not recognize. Some examples:

1. Misspelling a class / method name:

Console.WrteLine("Hey");

When we run this code we'll get an error CS0117: 'Console' does not contain a definition for 'WrteLine'.

2. Using a non-existent variable / Misspelling a variable's name:

string animal = "parrot";
Console.WriteLine(aniimal);

When we run this code we'll get an error CS0103: The name 'aniimal' does not exist in the current context.


Assignment
Follow the Coding Tutorial and let's practice with errors!


Hint
Look at the examples above if you get stuck.


STEP 1 OF 1
    Ctrl + Enter to check