A program in C# is typically organized into 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 considered 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 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.
Variable Naming Rules
In C#, when naming variables, there are certain rules you must follow. Otherwise, the compiler will flag 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 miVariable and _contador are acceptable.
Furthermore, it is possible to use language keywords if prefixed with an at sign (@), as in @class.
There is no strict limit on the length of names, but it is recommended that they be descriptive for easier understanding.
C# is also case-sensitive, meaning miVariable and MIVARIABLE are considered different.
On the other hand, there are certain restrictions you should be aware of. Variable names cannot contain spaces, so mi variable is incorrect.
Reserved Keywords
C# has a set of reserved keywords that cannot be used as identifiers (names for variables, classes, methods, etc.). The complete list is presented below:
| Reserved Keyword | Reserved Keyword | Reserved Keyword |
|---|---|---|
| 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.
