Language: EN

csharp-sintaxis-basica

Introduction to the C# Course

A C# program is typically organized into source code files with the .cs extension.

It is not necessary to explicitly import files into others. Any file that is part of the project is taken into account by the others.

The basic structure of a C# program includes namespaces, classes, and methods. Let’s see a simple example:

using System;

namespace MyFirstProgram
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello, world!");
        }
    }
}

Use of curly braces {}

Curly braces {} are used to delimit code blocks in C#. This includes class definitions, methods, and control flow blocks like if, for, and while.

class Example
{
    void Method()
    {
        if (true)
        {
            // If block of code
        }
    }
}

Use of the semicolon ;

In C#, each statement must end with a semicolon (;). This includes variable declarations, method calls, and other operations.

int x = 10; // Variable declaration with semicolon
Console.WriteLine(x); // Method call with semicolon

Forgetting the semicolon results in a compilation error.

Naming Rules for Variables in C#

In C#, when naming variables, there are certain rules you must follow. Otherwise, the compiler will mark it as an error.

First, valid characters include letters (both uppercase and lowercase), numbers, and the underscore _. However, names cannot start with a number. For example, names like myVariable and _counter are acceptable.

Additionally, it is possible to use keywords of the language if prefixed with an at symbol (@), as in @class.

There is no strict limit on the length of names, but it is advisable that they are descriptive for easier understanding.

C# is also case-sensitive, meaning that myVariable and MYVARIABLE are considered different.

On the other hand, there are certain restrictions you must keep in mind. Variable names cannot contain spaces, so my variable is incorrect.

Reserved Words

C# has a set of reserved words that cannot be used as identifiers (variable names, classes, methods, etc.). Below is the complete list:

Reserved WordReserved WordReserved Word
abstract@public
asboolreadonly
basebreakref
bytecaseremove
catchcharreturn
checkedclasssbyte
constconstsealed
continuedecimalshort
defaultdelegatesizeof
dodoublestackalloc
elseenumstatic
eventexplicitstring
externfalsestruct
finallyfixedswitch
floatforthis
foreachgotothrow
ifimplicittrue
ininttry
interfaceinternaltypeof
islockuint
longnamespaceulong
newnullunchecked
objectoperatorunsafe
outoverrideushort
paramsprivateusing
varprotectedvirtual
voidvolatilewhile

These words have a special meaning in the language and cannot be used as names for variables, functions, classes, etc.