Home > Backend Development > C++ > How Can I Return Multiple Values from a Method in C#?

How Can I Return Multiple Values from a Method in C#?

Patricia Arquette
Release: 2025-01-31 19:56:09
Original
214 people have browsed it

How Can I Return Multiple Values from a Method in C#?

C# method Returns multiple values ​​

Whether the C# method can return multiple values ​​has always been the focus of discussion of developers. This article will explore this concept in depth and clarify the feasibility of achieving this goal in C#.

C# 7's powerful features of the Yuan Group

C# 7 introduced the meta -group, making the long -awaited characteristic of returning multiple values ​​became a reality. The Yuan group provides an elegant mechanism for returning multiple values ​​from the method.

Create and return to the Yuan Group

To use the method to return multiple values ​​from the method, just define the return type as the meta -group. Each element in the tuple represents a value that is returned. For example, the following method returns a person's name, middle name, and surname:

Value in the access group

1

2

3

4

5

(string, string, string) LookupName(long id)

{

    // 从数据存储中检索名、中间名和姓

    return (first, middle, last);

}

Copy after login
In calling code, you can use indexes (for example, "ITEM1", "Item2", etc. or using naming elements (if you sign or return in the method of the method) to access the value of the tuple. Examples as follows: <下>

<命> Naming element elements

You can also provide a name for the elements of the tuple, making it more convenient to access them:

1

2

var names = LookupName(id);

Console.WriteLine($"找到 {names.Item1} {names.Item3}。");

Copy after login

<构> deconstructing and the Yuan group

C# also supports deconstruction, allowing you to easily assign the elements of the tuple to a separate variable. For example, the following code decompose the quotation of the LookupName method:

1

2

3

4

5

(string first, string middle, string last) LookupName(long id)

{

    // 从数据存储中检索名、中间名和姓

    return (first, middle, last);

}

Copy after login
More examples

To learn more about the tuples in C#, please access the following links: (here should be added to the relevant link here, the original text is not provided)

The above is the detailed content of How Can I Return Multiple Values from a Method in C#?. For more information, please follow other related articles on the PHP Chinese website!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template