Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
CSharpNotesForProfessionals.pdf
Скачиваний:
57
Добавлен:
20.05.2023
Размер:
6.12 Mб
Скачать

Chapter 124: Function with multiple return values

Section 124.1: "anonymous object" + "dynamic keyword" solution

You can return an anonymous object from your function

public static object FunctionWithUnknowReturnValues ()

{

/// anonymous object

return new { a = 1, b = 2 };

}

And assign the result to a dynamic object and read the values in it.

/// dynamic object

dynamic x = FunctionWithUnknowReturnValues();

Console.WriteLine(x.a);

Console.WriteLine(x.b);

Section 124.2: Tuple solution

You can return an instance of Tuple class from your function with two template parameters as Tuple<string, MyClass>:

public Tuple<string, MyClass> FunctionWith2ReturnValues ()

{

return Tuple.Create("abc", new MyClass());

}

And read the values like below:

Console.WriteLine(x.Item1);

Console.WriteLine(x.Item2);

Section 124.3: Ref and Out Parameters

The ref keyword is used to pass an Argument as Reference. out will do the same as ref but it does not require an assigned value by the caller prior to calling the function.

Ref Parameter: If you want to pass a variable as ref parameter then you need to initialize it before you pass it as ref parameter to method.

Out Parameter: If you want to pass a variable as out parameter you don’t need to initialize it before you pass it as out parameter to method.

static void Main(string[] args)

{

int a = 2; int b = 3; int add = 0; int mult= 0;

GoalKicker.com – C# Notes for Professionals

629

AddOrMult(a, b, ref add, ref mult); //AddOrMult(a, b, out add, out mult);

Console.WriteLine(add); //5 Console.WriteLine(mult); //6

}

private static void AddOrMult(int a, int b, ref int add, ref int mult) //AddOrMult(int a, int b, out int add, out int mult)

{

add = a + b; mult = a * b;

}

GoalKicker.com – C# Notes for Professionals

630