RUVIDEO
Поделитесь видео 🙏

Part 69 Making method parameters optional by specifying parameter defaults

Tags
c# 4.0 named and optional parameters
c# optional parameters named
c# named parameters example
c# method named parameters
c# function named parameters
named parameters c# example
c# method default parameters
c# optional parameters default value
optional parameters must specify a default value
c# named parameters method

C#, SQL Server, WCF, MVC and ASP .NET video tutorials for beginners
http://www.youtube.com/user/kudvenkat/playlists

Healthy diet is very important both for the body and mind. If you like Aarvi Kitchen recipes, please support by sharing, subscribing and liking our YouTube channel. Hope you can help.
https://www.youtube.com/channel/UC7sEwIXM_YfAMyonQCrGfWA/?sub_confirmation=1

In this video, we will discuss making method parameters optional by specifying parameter defaults.

This method allows us to add any number of integers.
public static void AddNumbers(int firstNumber, int secondNumber,
int[] restOfTheNumbers)
{
int result = firstNumber + secondNumber;
foreach (int i in restOfTheNumbers)
{
result += i;
}

Console.WriteLine("Total = " + result.ToString());
}

If we want to add 5 integers - 10, 20, 30, 40 and 50. We call the method as shown below.
AddNumbers(10, 20, new int[]{30, 40, 50});

At the moment all the 3 parameters are mandatory. If I want to add just 2 numbers, then I can invoke the method as shown below. Notice that, I am passing an empty integer array as the argument for the 3rd parameter.
AddNumbers(10, 20, new int[]{});

We can make the 3rd parameter optional by specify a default value of null for the 3rd parameter.
public static void AddNumbers(int firstNumber, int secondNumber,
int[] restOfTheNumbers = null)
{
int result = firstNumber + secondNumber;

// loop thru restOfTheNumbers only if it is not null
// otherwise you will get a null reference exception
if (restOfTheNumbers != null)
{
foreach (int i in restOfTheNumbers)
{
result += i;
}
}
Console.WriteLine("Total = " + result.ToString());
}

Since we have specified a default value for the 3rd parameter, it is optional. So, if we want to add just 2 numbers, we can use the function as shown below.
AddNumbers(10, 20);

Optional parameters must appear after all required parameters
The following method will not comiple. This is because, we are making parameter "a" optional, but it appears before the required parameters "b" and "c".
public static void Test(int a = 10, int b, int c)
{
// Do something
}

The following method will compile, as optional parameter "a" is specified after all the required parameters ("b" & "c").
public static void Test(int b, int c, int a = 10)
{
// Do something
}

Named Parameters
In the following method, parameters "b" & "c" are optional.
public static void Test(int a, int b = 10, int c = 20)
{
Console.WriteLine("a = " + a);
Console.WriteLine("b = " + b);
Console.WriteLine("c = " + c);
}

When we invoke this method as shown below, "1" is paased as the argument for parameter "a" and "2" is passed as the argument for parameter "b" by default.
Test(1, 2);

My intention is to pass "2" as the argument for parameter "c". To achieve this we can make use of named parameters, as shown below. Notice that, I have specified the name of the parameter for which value "2" is being passed.
Test(1, c: 2);

Что делает видео по-настоящему запоминающимся? Наверное, та самая атмосфера, которая заставляет забыть о времени. Когда вы заходите на RUVIDEO, чтобы посмотреть онлайн «Part 69 Making method parameters optional by specifying parameter defaults», вы рассчитываете на нечто большее, чем просто загрузку плеера. И мы это понимаем. Контент такого уровня заслуживает того, чтобы его смотрели в HD 1080, без дрожания картинки и бесконечного буферизации.

Честно говоря, Rutube сегодня — это кладезь уникальных находок, которые часто теряются в общем шуме. Мы же вытаскиваем на поверхность самое интересное. Будь то динамичный экшн, глубокий разбор темы от любимого автора или просто уютное видео для настроения — всё это доступно здесь бесплатно и без лишних формальностей. Никаких «заполните анкету, чтобы продолжить». Только вы, ваш экран и качественный поток.

Если вас зацепило это видео, не забудьте взглянуть на похожие материалы в блоке справа. Мы откалибровали наши алгоритмы так, чтобы они подбирали контент не просто «по тегам», а по настроению и смыслу. Ведь в конечном итоге, онлайн-кинотеатр — это не склад файлов, а место, где каждый вечер можно найти свою историю. Приятного вам отдыха на RUVIDEO!

Видео взято из открытых источников Rutube. Если вы правообладатель, обратитесь к первоисточнику.