0

C# Coffee Time Code Project

I solved the last Code Project in this way: int discount = 10; //Convert.ToInt32(Console.ReadLine()); Dictionary<string, int> coffee = new Dictionary<string, int>(); coffee.Add("Americano", 50); coffee.Add("Latte", 70); coffee.Add("Flat White", 60); coffee.Add("Espresso", 60); coffee.Add("Cappuccino", 80); coffee.Add("Mocha", 90); foreach (var item in coffee) { Console.WriteLine(item.Key + ": " + (item.Value - (item.Value * discount / 100))); } but others solve the foreach like this: //foreach (KeyValuePair<string, int> entry in coffee) //{ // Console.WriteLine(entry.Key + ": " + (entry.Value - entry.Value * discount / 100)); //} what is the difference? Is it the performance?

24th Jun 2022, 8:43 PM
Sam
Sam - avatar
3 Answers
+ 2
There is no run time difference C# handles var at compile time. https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/var For .Net 6 var gives a nullable reference type. Where explicit typing is only nullable, if you use the nullable postscript (type?). This difference won't affect running in Sololearn, since it uses an old version of .Net The benefit being you can use var x = new Type(). This way you do not have to spell the type out twice. As for the for each loop it will come down to user preferences, since there is no run time difference. If you are on a dev team, they may have a convention to follow. Personally I feel using var is more clean. And if you use an IDE it will help you keep track of the type without having to write it down everywhere to remember it.
25th Jun 2022, 3:54 AM
Adam McGregor
+ 3
You are using var item where type of item is automatically determined in compiling.. But others specifying it manually as it is KeyValuePair<strong, int> type data.. edit: yes. I mean when compiling and executing.. so compile time is correct. not run time.
24th Jun 2022, 9:14 PM
Jayakrishna 🇼🇳
- 2
hi
25th Jun 2022, 6:40 PM
Ű§Ù… Ű·Ù‡
Ű§Ù… Ű·Ù‡ - avatar