A C# program typically is organized in source code files with the .cs
extension.
There is no need 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 look at a simple example:
using System;
namespace MyFirstProgram
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello, world!");
}
}
}
Use of braces {}
Braces {}
are used to delimit blocks of code in C#. This includes class definitions, methods, and control flow blocks such as if
, for
, and while
.
class Example
{
void Method()
{
if (true)
{
// Code block of the if
}
}
}
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.
Variable Naming Rules 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.
Also, it is possible to use language keywords if prefixed with an at symbol (@), like in @class
.
There is no strict limit on the length of names, but it is advisable that they are descriptive for better understanding.
C# is also case-sensitive, meaning that myVariable
and MYVARIABLE
are considered different.
On the other hand, there are certain restrictions to 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.