What is Using declaration?
In C# 8.0, there are two new capabilities added around the 'Using' statement in order to make resource management simpler -
- 'Using' should recognize a disposable pattern in addition to 'IDisposable'
- Add a 'using' declaration to the language.
This new feature allows the developers to use 'using' in the local variable declaration. It has the same effect as that of the previous 'using' statements, like in the following example.
Old 'using' statement
- using(var fileStream = new FileStream("abcd.txt",FileMode.Open))
- {
-
- }
New 'using' statement
- var fileName = "abcd.txt";
- if(fileName != null)
- {
- using var fileStream = new FileStream(fileName, FileMode.Open);
-
-
- }
The lifetime of the 'using' local variable is the end of the scope where it is declared in the above example. Its scope is limited to the only if block. After the if block, it disposes of using the local variable. It disposes the 'using' local variables in reverse order of its declaration. Let us see the below example.
- var fileName = "abcd.txt";
- if(fileName != null)
- {
- using var fileStream1 = new FileStream(fileName, FileMode.Open);
- using var fileStream2 = new FileStream(fileName, FileMode.Open);
- using var fileStream3 = new FileStream(fileName, FileMode.Open);
-
-
-
-
-
-
- }
What is Static local function?
In this new feature, you can now add the 'static' modifier to the local function. It can not access any variable from the enclosing scope. In C# 7.0, we can access the variable from enclosing scope as follows.
- static void Main(string[] args)
- {
- var firstName = "Jeetendra";
- var lastName = "Gund";
-
- Console.WriteLine("My name is " + GetFullName()); //output My name is Jeetendra Gund
-
- string GetFullName() => firstName + ' ' + lastName;
- }
Now, in C# 8.0, we can add 'static' modifier to local function then the above example firstName and lastName won't be accessible there in GetFullName local function as follows:
- static void Main(string[] args)
- {
- var firstName = "Jeetendra";
- var lastName = "Gund";
-
- Console.WriteLine("My name is " + GetFullName());
-
- static string GetFullName() => firstName + ' ' + lastName;
- }
After compiling this we will get the below errors,
Let's resolve the above errors as follows,
- static void Main(string[] args)
- {
- var firstName = "Jeetendra";
- var lastName = "Gund";
-
- Console.WriteLine("My name is " + GetFullName(firstName, lastName)); //output My name is Jeetendra Gund
-
- static string GetFullName(string firstName, string lastName) => firstName + ' ' + lastName;
- }
You can also download all these examples from here.
Summary
In this article, we discussed what Using declarations and Static local functions in C# 8.0 are and how to use this with examples. If you have any suggestions or queries regarding this article, please contact me.
Stay tuned for other concepts of C# 8.0.
“Learn It, Share it.”