DEV Community

Cover image for C# Tips and Tricks - Part 2
Mohamad Lawand
Mohamad Lawand

Posted on

C# Tips and Tricks - Part 2

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:
https://github.com/mohamadlawand087/v34-CodeTipsTricks-Ep2

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

GetMyName("Mohamad");

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();
WriteLine(email);
Enter fullscreen mode Exit fullscreen mode

Please comment your questions as well subscribe to my YouTube channel

Top comments (0)