Why does this code output 15? Also, what's the difference between "int" and "var" keywords in C#? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 4

Why does this code output 15? Also, what's the difference between "int" and "var" keywords in C#?

int [] arr = {10, 15, 16}; var x = arr.FirstOrDefault( z => z.Equals(14)); Console.WriteLine(x + 15);

7th Jan 2021, 11:06 AM
eMBee
eMBee - avatar
3 Answers
+ 12
As I read, FirstOrDefault method is a part of System.Linq and is similar to First but the only difference is, it also handles empty collection. If a collection is empty then this method returns the default value for the type. https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.firstordefault?view=net-5.0 In your code you're checking if any value of the int array is equal to 14 or not. There is no value in your array which is equal to 14 so the method FirstOrDefault being called on an empty integer array returns 0. So, var x = 0. Then you're doing Console.WriteLine(x+15) , which is nothing but 0+15 Hence output = 15. Next part : var is a data type and is used to declare implicitly typed local variable. Means you can write, var a = 1; var b = "string"; And the compiler will figure out the type of the variable at compilation time. Also you have to initialise the var variable at the time of declaration. While int is an Integer type that can only store integer values like 1,2 etc..
7th Jan 2021, 11:31 AM
Minho
Minho - avatar
+ 8
M○|-|FΞY 🇳🇬 Lol 😆😂 lecture! 😳😂 You're most welcome and thanks for *reading* my lecture 😁
7th Jan 2021, 1:11 PM
Minho
Minho - avatar
+ 2
Thank you for your lecture Minho 🇰🇷 You made it crystal clear
7th Jan 2021, 1:09 PM
eMBee
eMBee - avatar