« Using » : différence entre les versions

De Banane Atomic
Aller à la navigationAller à la recherche
Aucun résumé des modifications
Aucun résumé des modifications
 
Ligne 1 : Ligne 1 :
[[Category:CSharp]]
= Définition =
Définit la portée d'un objet.<br>
Définit la portée d'un objet.<br>
A la sortie du {{boxx|using}}, la méthode {{boxx|Dispose}} sera appelée sur cet objet.<br>
A la sortie du {{boxx|using}}, la méthode {{boxx|Dispose}} sera appelée sur cet objet.<br>
Ligne 6 : Ligne 8 :


<kode lang="csharp">
<kode lang="csharp">
using(SqlConnection sqlConnection = new SqlConnection(connectionString))
// new syntax since C# 8
// the connection will be closed at the end of the local scope like the current method
using var sqlConnection = new SqlConnection(connectionString);
 
using(var sqlConnection = new SqlConnection(connectionString))
{
{
     // appel de sqlConnection.Dispose() à la fin du bloc using
     // appel de sqlConnection.Dispose() à la fin du bloc using
Ligne 12 : Ligne 18 :
}
}
</kode>
</kode>
[https://msdn.microsoft.com/en-us/library/aa664736%28v=vs.71%29.aspx?f=255&MSPPError=-2147217396 The using statement]
[[Category:CSharp]]

Dernière version du 13 mars 2023 à 15:00

Définition

Définit la portée d'un objet.
A la sortie du using, la méthode Dispose sera appelée sur cet objet.
L'objet fourni à l'instruction using doit donc implémenter l'interface IDisposable.
La levée d'un exception dans le bloc using provoque la sortie du bloc et donc l'appel de la méthode Dispose.
C'est l'équivalent d'un bloc try finally { Dispose } .

Csharp.svg
// new syntax since C# 8
// the connection will be closed at the end of the local scope like the current method
using var sqlConnection = new SqlConnection(connectionString);

using(var sqlConnection = new SqlConnection(connectionString))
{
    // appel de sqlConnection.Dispose() à la fin du bloc using
    // ou si une exception est levée
}