| by Arround The Web | No comments

How to Properly Use the ‘Using’ Statement in C#

The “using” keyword in C# is a fundamental feature that allows us to remove the complexity of resource management, for example, in objects that implement the IDisposable interface.

The role of the “using” keyword is to ensure that the allocated resources are released properly they are when no longer in need. This helps to improve the memory management and prevent the resource leaks.

In this tutorial, we will explore the various uses of the “using” keyword in C# and explore the various techniques where each usage is applicable.

C# IDisposable

Before we dive into the usage of the “using” statement, let us first try and understand the IDisposable interface.

In C#, any class that implements the IDisposable interface has a “Dispose” method that is responsible for releasing the resources such as files, database connections, network sockets, and more.

The following shows a basic class that implements the IDisposable interface:

class DisposableResource: IDisposable
{
    // Constructor, members, etc
    public void Dispose()
    {
        // Release unmanaged resources here
    }
}

Once the object goes out of scope, the “Dispose” method is called explicitly to release the resources. Also, keep in mind that this method is also called when an exception occurs when using the resource.

The following example shows how to use the “using” keyword for resource management:

using System;
using System.Text;
using System.IO;
class Program
{
    static void Main()
    {
        var path = "hello.txt";
        using var fs = new FileStream(path, FileMode.Open, FileAccess.Read);
        using var sr = new StreamReader(fs, Encoding.UTF8);
        string content = sr.ReadToEnd();
        Console.WriteLine(content);
    }
}

In the given example, we use the “FileStream” and “StreamReader” to read a text file from the file system.

Both  the “FileSsystem” and “StreamReader” inherit the IDisposable interface. Hence, using the “using” statement, we ensure that the resources are released when the two objects are out of scope.

Instead of manually calling the “Dispose” method, C# provides a simple and intuitive method of reading a file. This automatically calls the “Dispose” method as follows:

using System.Text;
var path = "hello.txt";
string content = File.ReadAllText(path, Encoding.UTF8);
Console.WriteLine(content);

In this case, the “ReadAllText” method opens the specified file, reads the contents into a string, and then closes the file.

The “Using” Directive

The second usage of the “using” keyword in C# is using it as a directive. This serves a different purposes than using the “using” keyword as a statement.

Using the “using”  keyword as a directive allows us to include the namespaces in our C# project. This makes the various types and members from those namespaces accessible without using the fully qualified name.

Here is an example that shows us using the “using” keyword as a directive:

using System;
using System.Collections.Generic;
namespace MyNamespace
{
    class Program
    {
        static void Main()
        {
            DateTime currentDate = DateTime.Now;
            List<string> myList = new List<string>();
        }
    }
}

In the given example, the first and second line allows us to access the types and members from the “System” and “System.Collections.Generic” namespaces such as DateTime and List<T>, respectively.

Using the “using” directives helps keep the code cleaner and more readable as we don’t need to fully qualify the types from these namespaces every time we wish to use them.

A common example of using the “using” keyword as a directive is when accessing the “WriteLine” method.

Without the “using” directive, we have to specify the fully qualified name as follows:

class Program
{
    static void Main()
    {
        System.Console.WriteLine("Hello, World!");
    }
}

In this example, we explicitly specify the “System” namespace when using the “Console.WriteLine”.

Creating Aliases with the Using Directive

We can also use the “using” directive to create aliases as shown in the following example:

using Print = System.Console;
Print.WriteLine("Hello, World");

The given example creates an alias for the “System.Console” to print.

Using the Static Directive

Since C# version 6.0, we can use the “using” keyword to import the static members such as methods, properties, and fields of a class without having to prefix them with the class name.

Example:

using static System.Math;
Console.WriteLine(Sqrt(141));

In the example, we import the “Sqrt” method.

Conclusion

In this tutorial, we explored the workings of the “using” keyword in C# as a namespace, as a directive, to create aliases, and using it as a static directive.

Share Button

Source: linuxhint.com

Leave a Reply