Skip to main content
Redhat Developers  Logo
  • Products

    Featured

    • Red Hat Enterprise Linux
      Red Hat Enterprise Linux Icon
    • Red Hat OpenShift AI
      Red Hat OpenShift AI
    • Red Hat Enterprise Linux AI
      Linux icon inside of a brain
    • Image mode for Red Hat Enterprise Linux
      RHEL image mode
    • Red Hat OpenShift
      Openshift icon
    • Red Hat Ansible Automation Platform
      Ansible icon
    • Red Hat Developer Hub
      Developer Hub
    • View All Red Hat Products
    • Linux

      • Red Hat Enterprise Linux
      • Image mode for Red Hat Enterprise Linux
      • Red Hat Universal Base Images (UBI)
    • Java runtimes & frameworks

      • JBoss Enterprise Application Platform
      • Red Hat build of OpenJDK
    • Kubernetes

      • Red Hat OpenShift
      • Microsoft Azure Red Hat OpenShift
      • Red Hat OpenShift Virtualization
      • Red Hat OpenShift Lightspeed
    • Integration & App Connectivity

      • Red Hat Build of Apache Camel
      • Red Hat Service Interconnect
      • Red Hat Connectivity Link
    • AI/ML

      • Red Hat OpenShift AI
      • Red Hat Enterprise Linux AI
    • Automation

      • Red Hat Ansible Automation Platform
      • Red Hat Ansible Lightspeed
    • Developer tools

      • Red Hat Trusted Software Supply Chain
      • Podman Desktop
      • Red Hat OpenShift Dev Spaces
    • Developer Sandbox

      Developer Sandbox
      Try Red Hat products and technologies without setup or configuration fees for 30 days with this shared Openshift and Kubernetes cluster.
    • Try at no cost
  • Technologies

    Featured

    • AI/ML
      AI/ML Icon
    • Linux
      Linux Icon
    • Kubernetes
      Cloud icon
    • Automation
      Automation Icon showing arrows moving in a circle around a gear
    • View All Technologies
    • Programming Languages & Frameworks

      • Java
      • Python
      • JavaScript
    • System Design & Architecture

      • Red Hat architecture and design patterns
      • Microservices
      • Event-Driven Architecture
      • Databases
    • Developer Productivity

      • Developer productivity
      • Developer Tools
      • GitOps
    • Secure Development & Architectures

      • Security
      • Secure coding
    • Platform Engineering

      • DevOps
      • DevSecOps
      • Ansible automation for applications and services
    • Automated Data Processing

      • AI/ML
      • Data Science
      • Apache Kafka on Kubernetes
      • View All Technologies
    • Start exploring in the Developer Sandbox for free

      sandbox graphic
      Try Red Hat's products and technologies without setup or configuration.
    • Try at no cost
  • Learn

    Featured

    • Kubernetes & Cloud Native
      Openshift icon
    • Linux
      Rhel icon
    • Automation
      Ansible cloud icon
    • Java
      Java icon
    • AI/ML
      AI/ML Icon
    • View All Learning Resources

    E-Books

    • GitOps Cookbook
    • Podman in Action
    • Kubernetes Operators
    • The Path to GitOps
    • View All E-books

    Cheat Sheets

    • Linux Commands
    • Bash Commands
    • Git
    • systemd Commands
    • View All Cheat Sheets

    Documentation

    • API Catalog
    • Product Documentation
    • Legacy Documentation
    • Red Hat Learning

      Learning image
      Boost your technical skills to expert-level with the help of interactive lessons offered by various Red Hat Learning programs.
    • Explore Red Hat Learning
  • Developer Sandbox

    Developer Sandbox

    • Access Red Hat’s products and technologies without setup or configuration, and start developing quicker than ever before with our new, no-cost sandbox environments.
    • Explore Developer Sandbox

    Featured Developer Sandbox activities

    • Get started with your Developer Sandbox
    • OpenShift virtualization and application modernization using the Developer Sandbox
    • Explore all Developer Sandbox activities

    Ready to start developing apps?

    • Try at no cost
  • Blog
  • Events
  • Videos

C# 9 top-level programs and target-typed expressions

March 30, 2021
Tom Deseyn
Related topics:
.NET

Share:

    .NET 5 (released in November 2020) includes support for C# 9, a major new version of the C# programming language. This series of articles explores the new features in .NET’s main programming language. In this first article, we’ll look at top-level statements and target-typed new and conditional expressions. These features make C# less verbose and can be used in everyday programs.

    Read the whole series

    Read the other articles in this series introducing new features in C# 9:

    • Part 2: C# 9 pattern matching
    • Part 3: C# 9 new features for methods and functions
    • Part 4: C# 9 init accessors and records
    • Part 5: Some more C# 9

    Additionally, last year, we published a series about C# 8. You can find those articles here:

    • Part 1: C# 8 asynchronous streams
    • Part 2: C# 8 pattern matching
    • Part 3: C# 8 default interface methods
    • Part 4: C# 8 nullable reference types
    • Part 5: Some more C# 8

    Top-level programs

    Top-level programs allow you to write the main method of your application without having to add a class with a static Main method. For example:

    // using directives
    using static System.Console;
    using System.Threading.Tasks;
     
    // program statements
    await Task.Delay(100);
    WriteLine("Hello " + (args.Length > 0 ? args[0] : "world!"));
    return 0;
    
    // local functions 
    // class/namespace declarations
    void Foo() { }
    class Foo { }
    

    The program statements are added directly in the C# file without an enclosing method, class, or namespace. You can place using directives before the program statements. Optionally, after the statements, you can define local functions, types, and namespaces.

    The example also shows some interesting features of top-level programming. The program can be asynchronous: we can use the await keyword. Program arguments are available using the args parameter, and the program may return an exit code.

    Target-typed new expressions

    Since C# 3, we can omit the declaring type for variables using the var keyword. The compiler derives the type from the expression:

    var person = new Person();
    

    With C# 9, you can also omit the type from the new operator, and make the compiler derive the type from the declaring type:

    Person p1 = new();
    Person p2 = new("Tom");
    Person p3 = new() { FirstName = "Tom" };
    

    The benefit of this syntax is that the type declarations are nicely aligned on the left-hand side. As you can see in the example, you can pass constructor arguments and use object initializers.

    Target-typed new expressions also work when you’re passing an argument to a method. However, it is less clear what type is constructed:

    PrintPerson(new());
    

    Target-typed conditional expressions

    With C# 9, the branches of ? .. : .. expressions are allowed to have different types, as long as both of them convert to the target type:

    Control c = true ? button : form;
    

    This example works in C# 9 even though button and form are of different types, because both convert to the target type (Control). Previously, the branches needed to have the exact same type, which required introducing casts when they didn’t match.

    Conclusion

    In this article, we looked at top-level programs, which make writing the main method less verbose. We also covered target-typed new expressions, which provide a nice syntax for aligning the types of variable declarations without having to duplicate the type for the new operator. And finally, we saw how target-typed conditional expressions allow us to omit casts when both branches convert to the target type.

    In the next article, we'll explore new features for pattern matching in C# 9.

    You can use C# 9 with the .NET 5 SDK, which is available on Red Hat Enterprise Linux, Red Hat OpenShift, Fedora, Windows, macOS, and other Linux distributions.

    Last updated: April 28, 2021

    Recent Posts

    • How to run a fraud detection AI model on RHEL CVMs

    • How we use software provenance at Red Hat

    • Alternatives to creating bootc images from scratch

    • How to update OpenStack Services on OpenShift

    • How to integrate vLLM inference into your macOS and iOS apps

    Red Hat Developers logo LinkedIn YouTube Twitter Facebook

    Products

    • Red Hat Enterprise Linux
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform

    Build

    • Developer Sandbox
    • Developer Tools
    • Interactive Tutorials
    • API Catalog

    Quicklinks

    • Learning Resources
    • E-books
    • Cheat Sheets
    • Blog
    • Events
    • Newsletter

    Communicate

    • About us
    • Contact sales
    • Find a partner
    • Report a website issue
    • Site Status Dashboard
    • Report a security problem

    RED HAT DEVELOPER

    Build here. Go anywhere.

    We serve the builders. The problem solvers who create careers with code.

    Join us if you’re a developer, software engineer, web designer, front-end designer, UX designer, computer scientist, architect, tester, product manager, project manager or team lead.

    Sign me up

    Red Hat legal and privacy links

    • About Red Hat
    • Jobs
    • Events
    • Locations
    • Contact Red Hat
    • Red Hat Blog
    • Inclusion at Red Hat
    • Cool Stuff Store
    • Red Hat Summit

    Red Hat legal and privacy links

    • Privacy statement
    • Terms of use
    • All policies and guidelines
    • Digital accessibility

    Report a website issue