C#10 new cool features in practice, part 1

C#10 new cool features in practice, part 1

In this article, we'll look at some most important C#10 features

  • Global Using Statements:

Adding using statements for some common libraries and namespaces like "System.Collections.Generic" or "System.Threading.Tasks" would be somehow frustrated, especially in middle level and big projects.

Now C# 10 comes with 2 cool features to ease this pain, One of them is using "global" modifier before a using statement in a separate .cs file.

global using System.Collections.Generic;

and the second cool way is adding it in your .csproj file by

<Using Include="System.Collections.Generic"/>

but don't forget to enable ImplicitUsings in .csproj.

  • File scope namespaces:

In previous versions of C#, using different namespaces was allowed, so you'd have something like this in your code file

namespace Linkedin
{
class WriteArticle
{...}
}
namespace Instagram
{
class Post
{...}
}

But in during more than 8 years of developing C#, I've never seen such a code file, and luckily c# developers found out that and add a possibility to have a single namespace in file scope, which led to code much being easier to read and decrease code lines:

using Linkedin;
class WriteArticle
{...}

  • Able to use string interpolation in Const variables

Before c#10 it wasn't possible to use string interpolation if the variable was constant like this:

const string Interpolated=$"{...}Mystring"

but now it's possible to define such a beautiful constant variable in c# 10.

  • Ability to have generic type Attributes

In the "Preview" version of the language, We can have generic type Attributes

class RezasArticleAttribute<T> : Attribute
{...}

  • Lambda return expression can be not defined

It was a huge pain when you came to writing a lambda function

func<string> HandleError = ()=> "Error handled";

We had to define its return type clearly and then write the rest of the expression, but now simply its this code id valid

var HandleError = ()=> "Error handled";


要查看或添加评论,请登录

社区洞察

其他会员也浏览了