In C#, one approach to return multiple values without classes, ref, or out keywords is by utilizing tuples. Tuples allow combining multiple values into a single return value. Here’s an example demonstrating this technique:
using System;class Program{ static (int, string) GetMultipleValues() { int number = 10; string text = "Hello"; return (number, text); } static void Main() { var result = GetMultipleValues(); Console.WriteLine($"Number: {result.Item1}, Text: {result.Item2}"); }}
using System;
class Program
{
static (int, string) GetMultipleValues()
int number = 10;
string text = "Hello";
return (number, text);
}
static void Main()
var result = GetMultipleValues();
Console.WriteLine($"Number: {result.Item1}, Text: {result.Item2}");
The GetMultipleValues method returns a tuple containing an integer and a string. By deconstructing the tuple, you can access the individual values. Tuples provide a concise way to return multiple values without the need for additional classes or keywords.
Using Tuple
We can use tuple in that case if we return multiple values same as well as different Data type
using System; using System.Collections.Generic; using System.Linq; using Internal;public class Program {public static void Main(string[] args){Abc abc = new Abc();var multiResult = abc.MultiResult(new List() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 });Console.WriteLine("First Result = " multiResult.TotalOfRecords);Console.WriteLine("Second Result = " multiResult.SumOfRecords);Console.ReadLine();}public class Abc{public (int TotalOfRecords, int SumOfRecords) MultiResult(List list){var noOfRecords = list.Count;var sum = list.Sum();return (noOfRecords, sum);}} }
You can return multiple values from a method without using classes, ref, or out keywords by utilizing tuples. Tuples are lightweight data structures that allow you to combine multiple values into a single object.