+ 9

Help with understanding the solution.

Hello sololearners. Given the code: static int Func(int a =3, int b = 7, int c = 6){ return a+b*c; } static void Main(string[] args) { int a = 4; int b = 5; int c = 2; Console.Write(Func(c, b)); // it's 32 } Please, can anyone explain why the answer is 32? How the main method calls the Func so we get 32? Please?

11th Apr 2017, 5:08 PM
Elena
Elena - avatar
13 ответов
+ 17
Func(c,b) is the same as Func(2,5) In the Func method, you have optional parameters. It has 3 parameters, but you only gave 2 (i.e. 2 and 5). So the third parameter by default is 6, because int c = 6. So Func(2,5) is actually Func(2,5,6) which is 32 😀
11th Apr 2017, 5:16 PM
Jafca
Jafca - avatar
+ 14
When called by main method the arguments are a=2 (replaces default value), b=5 (replaces default value) and c=6 (still default value, because no other value is passed). It returns 2+5*6 then, which results in 32: 5*6=30 (calculated first, because of the precedence of * over +) 30+2=32.
11th Apr 2017, 5:14 PM
Tashi N
Tashi N - avatar
+ 13
@Elena If you want, you can insert your code into your question so others can run it. E.g. https://code.sololearn.com/ci0rLWK9m3Bx/?ref=app
11th Apr 2017, 5:22 PM
Jafca
Jafca - avatar
+ 12
@Aditya, I read your post. Should I downvote now?
11th Apr 2017, 5:22 PM
Jafca
Jafca - avatar
+ 12
Your most welcome ^^
11th Apr 2017, 5:24 PM
Tashi N
Tashi N - avatar
+ 8
Oh, thank you all. So very helpful and quick. I feel like hugging you! 😊
11th Apr 2017, 5:23 PM
Elena
Elena - avatar
+ 7
@Jafca, Thanks, new feature. Good to know ^^
11th Apr 2017, 5:25 PM
Elena
Elena - avatar
+ 4
@Mike, you can post your code here so we could help you.
13th Apr 2017, 2:07 AM
Elena
Elena - avatar
+ 4
Value passing (2,5) and third value is default as (6), and calculation goes on as 2+(5*6)=2+30=32
13th Apr 2017, 3:39 PM
Himanshu Bhandari
Himanshu Bhandari - avatar
+ 2
The names of variables don't mean anything in different contexts. In your case, you passed 2 parameters to the function. They will replace the 2 first parameters. Third one will be defaulted. 2 + 5 * 6 = 32. The variable names were only used to confuse you.
11th Apr 2017, 5:22 PM
Denis Felipe
Denis Felipe - avatar
+ 2
In Func c - is a (2), b - is b (5), c is the default (6)
11th Apr 2017, 5:52 PM
Eugene Stolle
0
when I try to declare a variable as a parameter IE. Func(a=3) it says ; expected
12th Apr 2017, 8:55 PM
Mike
Mike - avatar
0
hello
13th Apr 2017, 4:21 AM
Shirani Shirani
Shirani Shirani - avatar