What's New With C# 8.0 – Using Declaration | Syncfusion Blogs
Live Chat Icon For mobile
Live Chat Icon
Popular Categories.NET  (175).NET Core  (29).NET MAUI  (208)Angular  (109)ASP.NET  (51)ASP.NET Core  (82)ASP.NET MVC  (89)Azure  (41)Black Friday Deal  (1)Blazor  (220)BoldSign  (15)DocIO  (24)Essential JS 2  (107)Essential Studio  (200)File Formats  (67)Flutter  (133)JavaScript  (221)Microsoft  (119)PDF  (81)Python  (1)React  (101)Streamlit  (1)Succinctly series  (131)Syncfusion  (920)TypeScript  (33)Uno Platform  (3)UWP  (4)Vue  (45)Webinar  (51)Windows Forms  (61)WinUI  (68)WPF  (159)Xamarin  (161)XlsIO  (37)Other CategoriesBarcode  (5)BI  (29)Bold BI  (8)Bold Reports  (2)Build conference  (8)Business intelligence  (55)Button  (4)C#  (151)Chart  (132)Cloud  (15)Company  (443)Dashboard  (8)Data Science  (3)Data Validation  (8)DataGrid  (63)Development  (633)Doc  (8)DockingManager  (1)eBook  (99)Enterprise  (22)Entity Framework  (5)Essential Tools  (14)Excel  (41)Extensions  (22)File Manager  (7)Gantt  (18)Gauge  (12)Git  (5)Grid  (31)HTML  (13)Installer  (2)Knockout  (2)Language  (1)LINQPad  (1)Linux  (2)M-Commerce  (1)Metro Studio  (11)Mobile  (508)Mobile MVC  (9)OLAP server  (1)Open source  (1)Orubase  (12)Partners  (21)PDF viewer  (43)Performance  (12)PHP  (2)PivotGrid  (4)Predictive Analytics  (6)Report Server  (3)Reporting  (10)Reporting / Back Office  (11)Rich Text Editor  (12)Road Map  (12)Scheduler  (52)Security  (3)SfDataGrid  (9)Silverlight  (21)Sneak Peek  (31)Solution Services  (4)Spreadsheet  (11)SQL  (11)Stock Chart  (1)Surface  (4)Tablets  (5)Theme  (12)Tips and Tricks  (112)UI  (387)Uncategorized  (68)Unix  (2)User interface  (68)Visual State Manager  (2)Visual Studio  (31)Visual Studio Code  (19)Web  (597)What's new  (333)Windows 8  (19)Windows App  (2)Windows Phone  (15)Windows Phone 7  (9)WinRT  (26)
csharp-using declaration

What’s New With C# 8.0 – Using Declaration

With the C# 8.0 update, Microsoft has introduced the using declaration feature. This feature allows us to declare a disposable object with the keyword using so the object will be disposed of when it goes out of the scope.

Using statement (classic approach)

In the classic approach, prior to the C# 8.0 update, we used a using statement to define the scope of the managed type objects that access unmanaged resources and the unmanaged resources that implement the IDisposable interface.

The following code example uses the classic approach in the creation of a text file.

static void CreateTextFileClassic()
{
    using (var file = new System.IO.StreamWriter("Sample.txt"))
    {
        file.WriteLine("Hello world");
    }// file object is disposed of here
}

Using declaration

Let’s see the same example but with the using declaration.

static void CreateTextFileModern()
{
    using var file = new System.IO.StreamWriter("Sample.txt");
    file.WriteLine("Hello world");    
    // file is disposed of here
}

At first glance, all of us would notice the missing curly braces. Before we jump to conclusions, let’s compile these code examples and refactor the resultant assembly. To our surprise, both sets of code resulted in the same piece of code.

private static void CreateTextFileClassic()
{
    using (StreamWriter file = new StreamWriter("Sample.txt"))
    {
        file.WriteLine("Hello world");
    }
}

private static void CreateTextFileModern()
{
    using (StreamWriter file = new StreamWriter("Sample.txt"))
    {
        file.WriteLine("Hello world");
    }
}

Comparing using declaration and using statement

Based on our understanding so far, the using declaration does not need us to define the scope of the object; it is instead handled by the compiler itself.

The scope of the object declared in the using statement is the scope in which it is declared.

Let’s consider the following scenario in which I am going to add a few more lines of code to see how the using declaration and using statements behave.

Using statement

The following code is implemented with the using statement:

static int CreateTextFileClassic(List lines)
{
    int addedLines = 0;
    using (var file = new System.IO.StreamWriter("Sample.txt"))
    {
        foreach (string line in lines)
            if (line.Contains("account number"))
            {
                file.WriteLine(line);
                addedLines++;
            }
    }
    return addedLines;
}

Using declaration

The following code is implemented with the using declaration:

static int CreateTextFileModern(List lines)
{
    int addedLines = 0;
    using var file = new System.IO.StreamWriter("Sample.txt");
    foreach (string line in lines)
        if (line.Contains("account number"))
        {
            file.WriteLine(line);
            addedLines++;
        }
    return addedLines;
}

Now let’s compile these code samples and refactor the resultant assembly to take a deeper look.

private static int CreateTextFileClassic(List lines)
{
	int addedLines = 0;
	using (StreamWriter file = new StreamWriter("Sample.txt"))
	{
		foreach (string line in lines)
		{
			if (line.Contains("account number"))
			{
				file.WriteLine(line);
				addedLines++;
			}
		}
	}
	return addedLines;
}

private static int CreateTextFileModern(List lines)
{
	int addedLines = 0;
	using (StreamWriter file = new StreamWriter("Sample.txt"))
	{
		foreach (string line in lines)
		{
			if (line.Contains("account number"))
			{
				file.WriteLine(line);
				addedLines++;
			}
		}
		return addedLines;
	}
}

Though these method looks similar, they are not. The scope of the using block in CreateTextFileModern is a bit larger than in CreateTextFileClassic.

Conclusion

In the case of a using statement, we have control over defining the scope of the object. In the case of a using declaration, its scope is automatically defined from the object’s declaration statement to the end of the current code block.

If the methods are going to be small and you are using the using declaration in the final part of the method, the new approach is well and good.

If you’re interested in other new features in C# 8.0, we have already published a blog on the nullable reference type feature. Refer to the blog What’s New with C# 8.0 – Nullable Reference Type for more details.

Syncfusion provides more than 1,000 custom controls to ease the work of developers on various platforms. Please have a look and use them in your application development:

If you have any questions or require clarifications about our components, please let us know in the comments below. You can also contact us through our support forumDirect-Trac, or feedback portal. We are happy to assist you!

Happy coding!

Tags:

Share this post:

Comments (2)

I definitely have to agree with your statement “If the methods are going to be small and you are using the using declaration in the final part of the method, the new approach is well and good.”

I can’t see the benefit of a using declaration over the using statement if the method does not conform in some part to SOLID principles. I have worked on legacy applications that contained pages and pages of (frustratingly) long methods.

If the using declaration keeps the variable in scope all the way to the bottom, then a using statement will make more sense to use because the object will be disposed of at the using statement’s ending brace.

Hi Dirk Strauss,
Yes, in long methods, it is highly recommended to use using statement instead using declaration in order to release the memory of the object at the earliest.
Regards,
Suresh

Comments are closed.

Popular Now

Be the first to get updates

Subscribe RSS feed

Be the first to get updates

Subscribe RSS feed