VARIABLES IN C SHARP
Variables in C Sharp are areas of memory in which a certain type of data is temporarily stored, they are the fundamental basis of the C# language, a variable can contain data of a type defined in the standard library such as an int (the keyword int indicates to the compiler that we are declaring an integer) or a type introduced by us. To declare a variable proceed as follows:
VARIABLES IN C SHARP – DECLARATION
int myVar ;
With this instruction which as you can see ends with a semicolon as we have seen regarding tokens, we indicate to the compiler that we need an integer type variable and which is identified by the name myVar. A memory area of 4 Bytes is set aside by the compiler since an int occupies 4 Bytes. Once the variable has been declared we must initialize it, that is, provide it with a value. This is done using the assignment operator. If we don’t do this we will have a compiler error.
myVar = 180 ;
At this point a certain area of RAM will contain the value 180 and this value will be accessible within the program by the myVar identifier. In practice, with the assignment operator which is the symbol =, the compiler takes the content of the part on the right (which can be a literal as in this case, or a complex expression, a method call, etc.) and assign to the part immediately to the left.
VARIABLES IN C SHARP DECLARATION AND INITIALIZATION
The declaration and initialization can be done in one go as follows:
int myVar = 180 ;
You can also declare multiple variables of the same type separated by a comma as in the following example:
int x , y, z;
In this case the compiler creates three distinct memory areas, identified by x, y, z. As in the case of a single variable, three variables can also be declared and initialized.
int x = 120 , y = 80 , z = 50 ;
Suppose we have the following variables:
int x = 180 ;
int y = 20 ;
What happens if we assign the value of x to y, that is, we use the following statement;
y = x;
In this case the compiler creates two copies for the variables, one copy that leaves the value of x 180 intact while y, given the assignment operation, will contain the value of x i.e. 180 and no longer 20.
By reassigning the value to x, this variable will contain the new value while y will remain intact at the value 180. Let’s verify everything written so far by creating a new project in visual studio code, a console application that we will call Variables.
INSIGHT ON VARIABLES IN C#
Variables in C# are used to store data of various types and can be of various types depending on the programmer’s needs. Here is an overview of the main variable types in C#:
Declaration of variables
To declare a variable in C#, you use the following syntax:
type variableName ;
Example:
int number ; //Declaration of an integer variable
string text ; //Declaration of a string variable
Types of variables
1. Value Types :
• int : stores integers (e.g. int number = 10; )
• float : stores single precision floating point numbers (e.g. float decimalnumber = 10.5f; )
• double : stores double precision floating point numbers (e.g. double doubleCommaNumber = 10.5; )
• bool : stores boolean values (true or false) (e.g. bool isTrue = true; )
• char : stores a single character (e.g. char letter = ‘A’; )
2. Reference Types :
• string : stores sequences of characters (e.g. string name = “Mario”; )
• object : base type of all types in C# (e.g. generic object = 42; )
Initialization of variables
A variable can be initialized at declaration time:
int number = 5;
string text = “Hello”;
Constant variables
Constant variables are variables whose value cannot be changed after initialization. They are declared using the const keyword:
const int daysWeek = 7;
const string greeting = “Hello, World!”;
Local variables
Variables declared within a method are called local variables and are accessible only within that method.
void ExampleMethod()
{
local int = 10;
Console.WriteLine(local);
}
Instance and class variables
• Instance variables : They are declared inside a class but outside any method. Each instance of the class has its own copy of these variables.
• Class variables : they are declared with the static keyword inside a class. There is only one copy of these variables, shared by all instances of the class.
Example:
class Person
{
public string name ; // Instance variable
public static int counter = 0; // Class variable
}
Nullable types
Value types in C# can be declared as nullable using the ? . This allows them to also represent the null value:
int? nullableNumber = null;
if (nullableNumber.HasValue)
{
Console.WriteLine(nullableNumber.Value);
}
else
{
Console.WriteLine(“The variable is null”);
}
Complete example
Here’s a complete example that illustrates various aspects of variables in C#:
using System; class Program { // Variabile di classe public static int contatore = 0; static void Main(string[] args) { // Variabile locale int numeroLocale = 42; // Variabile di istanza Persona persona = new Persona(); persona.nome = "Mario"; // Uso di variabili nullable int? etaNullable = null; if (!etaNullable.HasValue) { etaNullable = 30; } Console.WriteLine($"Nome: {persona.nome}, Età: {etaNullable.Value}"); // Conversione esplicita double decimale = 9.99; int intero = (int)decimale; Console.WriteLine($"Intero: {intero}"); // Variabile costante const string messaggio = "Ciao, mondo!"; Console.WriteLine(messaggio); contatore++; Console.WriteLine($"Contatore: {contatore}"); } } class Persona { // Variabile di istanza public string nome; }
VISUAL STUDIO CODE
using System; namespace Variabili { internal class Program { private static void Main(string[] args) { int myVar; //dichiarazione di una variabile //per i commenti su una riga anteponiamo il doppio slash//. //I commenti su più righe iniziano con /* e terminano con */ //Console.WriteLine($"myVar vale:{myVar}"); //PRODUCE UN ERRORE DI COMPILAZIONE, myVar non inizializzata. /*Come si vede provando ad utilizzare myVar senza averla inizializzata si produce un errore di compilazione subito segnalato da Visual Studio Code.*/ myVar = 120; Console.WriteLine($"myVar vale:{myVar}"); //dichiarazione e inizializzazione di più variabili su una riga. int x = 120, y = 180, z = 50; Console.WriteLine($"x:{x},y:{y},z:{z}"); //Assegiamo ad y il valore di x. y = x; Console.WriteLine($"y adesso vale:{y}, mentre x:{x}"); /*Come vedi per stampare a video i risultati ho utilizzato quella che viene chiamata interpolazione di stringhe. in pratica bisogna anteporre alla stringa il $ e usare i valori delle variabili tra parentesi graffe. C'è anche un altro metodo che ora ti faccio vedere e che si basa su segnaposti.*/ Console.WriteLine("y adesso vale:{0}, mentre x:{1}", y, x); } } }
Leave A Comment