W
W
whiskeyWithIce2019-09-19 10:32:54
.NET
whiskeyWithIce, 2019-09-19 10:32:54

Using implicit typing to determine the type of a loop variable?

I read off. C# manual ( Here ), and there it says:

It is recommended that you use implicit typing to determine the type of a loop variable in for and foreach loops.

For:
var phrase = "lalalalalalalalalalalalalalalalalalalalalalalalalalalalalala";
var manyPhrases = new StringBuilder();
for (var i = 0; i < 10000; i++)
{
    manyPhrases.Append(phrase);
}
//Console.WriteLine("tra" + manyPhrases);

Foreach:
foreach (var ch in laugh)
{
    if (ch == 'h')
        Console.Write("H");
    else
        Console.Write(ch);
}
Console.WriteLine();

And now I have a question, why is implicit typing recommended? If I specify int instead of var , then there may be some pitfalls or something like that? Or is it just accepted, and this is how it should be done, because everyone does it?)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
MrDywar Pichugin, 2019-09-19
@whiskeyWithIce

On the contrary, if you explicitly specify the type yourself, there will definitely be no problems.
It's just that var is a shorter notation, and is very often used when the type on the right is known exactly, or vice versa is unknown (anonymous var a = new { A = 1, B = 2}).
There may be problems with var , for example, when we expected FLOAT, but received DOUBLE (for this, you can either specify the type or use the F or D postfix). (var will be converted to the nearest enclosing type)
When I started learning C#, I also did not immediately understand what the joke was, but over time I switched to var myself .
The code is shorter and there is less duplicate information:
Customer c = new Customer();
var c = new Customer();
When to Use and Not Use var in C#

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question