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 new features for methods and functions

April 13, 2021
Tom Deseyn
Related topics:
.NET
Related products:
Developer Tools

Share:

    This is the third article in our C# 9 series. In the previous articles, we covered top-level programs and target-typed expressions and new features for pattern matching. In this article, we’ll look at new features for methods, anonymous functions, and local functions.

    Covariant return types

    When overriding base class members or implementing interfaces, C# 9 allows you to use a more specific return type:

    class Person
    {
     public virtual Person Clone() { ... }
    }
     
    class Student : Person
    {
     public override Student Clone() { ... }
    }
    

    In previous versions of C#, the return type had to match the base declaration. A cast was required in order to obtain the actual more specific type:

    Student clone = (Student)student.Clone();
    

    Static anonymous functions

    For a long time, C# has supported the declaration of anonymous functions using anonymous methods or lambda expressions:

    // Anonymous functions:
    // - C# 2.0: anonymous methods
    Func<string, int> = delegate(string arg) { return arg.Length; };
    // - C# 3.0: lambda expressions
    Func<string, int> = arg => arg.Length;
    

    Anonymous functions can use local variables. To disallow this, and require explicit passing of all arguments, we can now mark anonymous functions as static:

    // error CS8820: static anonymous function references ‘offset’
    int offset = 20;
    Func<string, int> d1 = static delegate(string arg) { return arg.Length + offset; };
    Func<string, int> d2 = static arg => arg.Length + offset;
    

    Attributes on local functions

    C# 7 introduced local functions, which are defined in the calling method. C# 8 enhanced these local functions and permitted them to be marked as static to disallow the use of local variables (similar to the previous section).

    C# 9 makes it possible to add attributes to local functions. The following example applies the DllImport attribute to a local function:

    public static void Terminate(this Process p)
    {
       const int SIGTERM = 15;
       kill(p.Id, SIGTERM);
     
       [DllImport("libc", SetLastError = true)]
       static extern int kill(int pid, int sig);
    }
    

    Extended partial methods

    To facilitate customizing generated code, C# 3 introduced the concept of partial methods.

    The generated C# code includes a method marked with partial with no body. The body for the method is provided by the user in a separate file.

    C# 3 doesn’t require the user to provide a body. When the code is compiled, the compiler uses the method that was provided by the user, or omits the calls if there is no such method.

    Because providing the implementation is optional, partial methods are not allowed to have output parameters or non-void return types:

    // -- MyForm.generated.cs --
    public partial class MyForm : Form
    {
       public MyForm()
       {
       	// ...
       	// generated code to initialize components.
       	// ...
     
       	OnComponentsInitialized();
       }
     
       partial void OnComponentsInitialized();
    }
     
    // -- MyForm.cs --
    public partial class MyForm
    {
       partial void OnComponentsInitialized()
       {
       	// user code
       }
    }
    

    C# 9 allows partial methods to have a return type and output parameters. The compiler requires there to be an implementation. This extended kind of partial method must have an accessibility modifier, which is no longer limited to private scope.

    This lets the user split the declaration of a method (the method signature) from its definition (the code).

    Extended partial methods go hand-in-hand with another new C# compiler feature: source generators. A source generator is code that runs during compilation to produce additional source code that gets compiled. You can learn more about source generators in Introducing C# Source Generators.

    As you probably guessed, a source generator is responsible for generating the implementation of partial methods. The following example shows a partial method that can cause a source generator to emit an implementation that is optimized for the regular expression provided in the RegexGenerated attribute:

    [RegexGenerated("(dog]
    public partial bool IsPetMatch(string input);
    

    Conclusion

    This article covered new capabilities for methods and functions in C# 9. We learned that overridden methods can now return more specific types, anonymous methods can be marked static to require passing in all parameters, and local functions can now have attributes. Finally, we looked at extended partial methods and how they are used with C# source generators.

    In the next article, we'll look at init accessors and records.

    C# 9 can be used with the .NET 5 SDK, which is available on Red Hat Enterprise Linux and Red Hat OpenShift, on Fedora, and from Microsoft for Windows, macOS, and other Linux distributions.

    Last updated: February 5, 2024

    Recent Posts

    • GuideLLM: Evaluate LLM deployments for real-world inference

    • Unleashing multimodal magic with RamaLama

    • Integrate Red Hat AI Inference Server & LangChain in agentic workflows

    • Streamline multi-cloud operations with Ansible and ServiceNow

    • Automate dynamic application security testing with RapiDAST

    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