Home > Backend Development > C++ > How Do Optional Parameters Work in C#?

How Do Optional Parameters Work in C#?

DDD
Release: 2025-01-23 05:11:09
Original
793 people have browsed it

How Do Optional Parameters Work in C#?

Optional parameters in C#

In earlier versions before C# 4.0, optional parameters were not supported. However, there are techniques to simulate them. One way is to overload the method with a different parameter list. For example:

<code class="language-c#">public void GetFooBar(int a)
{
    // GetFooBar 的单参数实现
}

public void GetFooBar(int a, int b)
{
    // GetFooBar 的双参数实现
}</code>
Copy after login

This allows you to call GetFooBar with one or two arguments, depending on your needs.

However, in C# 4.0 and later, optional parameters are directly supported using the following syntax:

<code class="language-c#">public void GetFooBar(int a, int b = 0)
{
    // GetFooBar 的可选参数实现
}</code>
Copy after login

In this example, if b is not provided when calling the method, it defaults to 0. You can specify any default value you want.

The above is the detailed content of How Do Optional Parameters Work in C#?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template