DEV Community

Cover image for C# Tips and Tricks - Part 2

C# Tips and Tricks - Part 2

Mohamad Lawand
Code is Life. Crossfitter. Solution Architect. Just another human walking the earth!
・2 min read

In this article we will be covering:

  • Top-level statements
  • Static directive

You can watch the full video on YouTube

You can get the source code on GitHub:

Top-level statements

they are new language features that got added in C# 9 and one of the goals to make it easier for beginners to jump start developing C# applications.

When writing top level statements i don't need to add all of the boiler plates code that i usually add when writing code.

using System;

Console.WriteLine("Hello world!");
Enter fullscreen mode Exit fullscreen mode

All of the boiler plates code will be automatically generated for us and we don't have to worry about creating it ourselfs.

Top-level statement also support async code

using System;
using System.Threading.Tasks;

Console.WriteLine("Wake up world!");
await Task.Delay(2000);
Console.WriteLine("Have breakfast");
Enter fullscreen mode Exit fullscreen mode

Now let us introduce methods


private static string GetMyName(string name)
    return $"Hello {name}, welcome to C# 9";
Enter fullscreen mode Exit fullscreen mode

Now lets run the application and see it in action.

The goal of Top level calls is to simplify this code and we can transform our application to something easy to read and understan

C# will assume this is the entry point to our application

Why use TLC

  • simplicity
  • quick to create
  • very simple to use in a none windows environment
  • easily created from within the terminal

Static directive

the using static directive allows us to use static types inside our applications without needing to referencing the type name everytime.

One common example of this is using Console application will allow us to read/write to line. but we need to add the Console type everytime we want to use. What if we can imply that we are using console type without having to write console everytime we use console.

using System;
using static System.Console;

WriteLine("Hello Static Directive");
var email = ReadLine();
Enter fullscreen mode Exit fullscreen mode

Please comment your questions as well subscribe to my YouTube channel

Discussion (0)