Skip to main content
Redhat Developers  Logo
  • AI

    Get started with AI

    • Red Hat AI
      Accelerate the development and deployment of enterprise AI solutions.
    • AI learning hub
      Explore learning materials and tools, organized by task.
    • AI interactive demos
      Click through scenarios with Red Hat AI, including training LLMs and more.
    • AI/ML learning paths
      Expand your OpenShift AI knowledge using these learning resources.
    • AI quickstarts
      Focused AI use cases designed for fast deployment on Red Hat AI platforms.
    • No-cost AI training
      Foundational Red Hat AI training.

    Featured resources

    • OpenShift AI learning
    • Open source AI for developers
    • AI product application development
    • Open source-powered AI/ML for hybrid cloud
    • AI and Node.js cheat sheet

    Red Hat AI Factory with NVIDIA

    • Red Hat AI Factory with NVIDIA is a co-engineered, enterprise-grade AI solution for building, deploying, and managing AI at scale across hybrid cloud environments.
    • Explore the solution
  • Learn

    Self-guided

    • Documentation
      Find answers, get step-by-step guidance, and learn how to use Red Hat products.
    • Learning paths
      Explore curated walkthroughs for common development tasks.
    • Guided learning
      Receive custom learning paths powered by our AI assistant.
    • See all learning

    Hands-on

    • Developer Sandbox
      Spin up Red Hat's products and technologies without setup or configuration.
    • Interactive labs
      Learn by doing in these hands-on, browser-based experiences.
    • Interactive demos
      Click through product features in these guided tours.

    Browse by topic

    • AI/ML
    • Automation
    • Java
    • Kubernetes
    • Linux
    • See all topics

    Training & certifications

    • Courses and exams
    • Certifications
    • Skills assessments
    • Red Hat Academy
    • Learning subscription
    • Explore training
  • Build

    Get started

    • Red Hat build of Podman Desktop
      A downloadable, local development hub to experiment with our products and builds.
    • Developer Sandbox
      Spin up Red Hat's products and technologies without setup or configuration.

    Download products

    • Access product downloads to start building and testing right away.
    • Red Hat Enterprise Linux
    • Red Hat AI
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform
    • See all products

    Featured

    • Red Hat build of OpenJDK
    • Red Hat JBoss Enterprise Application Platform
    • Red Hat OpenShift Dev Spaces
    • Red Hat Developer Toolset

    References

    • E-books
    • Documentation
    • Cheat sheets
    • Architecture center
  • Community

    Get involved

    • Events
    • Live AI events
    • Red Hat Summit
    • Red Hat Accelerators
    • Community discussions

    Follow along

    • Articles & blogs
    • Developer newsletter
    • Videos
    • Github

    Get help

    • Customer service
    • Customer support
    • Regional contacts
    • Find a partner

    Join the Red Hat Developer program

    • Download Red Hat products and project builds, access support documentation, learning content, and more.
    • Explore the benefits

C# 9 new features for methods and functions

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

    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

    • SQL Server HA on RHEL: Meet Pacemaker HA Agent v2 (tech preview)

    • Deploy with confidence: Continuous integration and continuous delivery for agentic AI

    • Every layer counts: Defense in depth for AI agents with Red Hat AI

    • Fun in the RUN instruction: Why container builds with distroless images can surprise you

    • Trusted software factory: Building trust in the agentic AI era

    Red Hat Developers logo LinkedIn YouTube Twitter Facebook

    Platforms

    • Red Hat AI
    • Red Hat Enterprise Linux
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform
    • See all products

    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
    © 2026 Red Hat

    Red Hat legal and privacy links

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

    Chat Support

    Please log in with your Red Hat account to access chat support.