Before we continue to FileInfo and Streams we need to explain using keyword in details.
Using directive
Using directive shortens our syntax so that we do not always have to type entire namespace:
1 2 3 4 5 |
// Without adding using directive to top of namespace using System.Collections.Generic; // We could create new list like this: System.Collections.Generic.List<string> newList = new System.Collections.Generic.List<string>(); // No penalties or errors will occur if we instantiate our List like that even if we use using directive. |
Using directive grants us access to static members having to qualify the access with the type name:
1 2 3 |
// Adding this using directive allows us to access Console class using System; // Console class is static class |
Using directive enables us to create alias directive.
1 2 |
using ListUsing = System.Collections.Generic; ListUsing.List<string> newList = new ListUsing.List<string>(); |
Using statement
Using statement provides us with a easy to use syntax which in return guarantees us with that types that implement IDisposable interface will be disposed of when we finish with them. For now do not stress yourself with questions like why do I need to dispose of something and what use IDisposable interface is to me. Those questions will be covered in a future post.
Example of using statement
Usage of using statement is straight-forward.
First we type using keyword and open parentheses, and inside of those brackets we instantiate class that implements IDisposable interface. After that we proceed to use class instance inside curly brackets.
1 2 3 4 |
using (ClassThatImplementsIDisposable myClass = new ClassThatImplementsIDisposable ()) { myClass.MethodInsideMyClass(); } |
Of-course you can instantiate more than one class while using using directive, just remember to separate them with coma:
1 2 3 4 5 6 |
using (ClassThatImplementsIDisposable myClass = new ClassThatImplementsIDisposable(), SecondClassThatImplementsIDisposable mySecondClass = new SecondClassThatImplementsIDisposable().) { myClass.Method(); mySecondClass.Metod5); } |
I hope you will find using keyword helpful. I certainly use it on a daily basis in both forms
Leave a Reply