7
Reply

How to Returning Multiple Values from method Without Using Class, ref, or out Keyword ?

Lalji Dhameliya

Lalji Dhameliya

Apr 16
2.4k
1
Reply

    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:

    1. using System;
    2. class Program
    3. {
    4. static (int, string) GetMultipleValues()
    5. {
    6. int number = 10;
    7. string text = "Hello";
    8. return (number, text);
    9. }
    10. static void Main()
    11. {
    12. var result = GetMultipleValues();
    13. Console.WriteLine($"Number: {result.Item1}, Text: {result.Item2}");
    14. }
    15. }

    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.

    By using tuple

    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.