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 Word | Reserved Word | Reserved Word |
---|---|---|
abstract | @ | public |
as | bool | readonly |
base | break | ref |
byte | case | remove |
catch | char | return |
checked | class | sbyte |
const | const | sealed |
continue | decimal | short |
default | delegate | sizeof |
do | double | stackalloc |
else | enum | static |
event | explicit | string |
extern | false | struct |
finally | fixed | switch |
float | for | this |
foreach | goto | throw |
if | implicit | true |
in | int | try |
interface | internal | typeof |
is | lock | uint |
long | namespace | ulong |
new | null | unchecked |
object | operator | unsafe |
out | override | ushort |
params | private | using |
var | protected | virtual |
void | volatile | while |
These words have a special meaning in the language and cannot be used as names for variables, functions, classes, etc.