[Don’t .NET] No var for You!

Guriy Samarin
Dec 15, 2024

--

Did you know that the following code

for(int i = 0; i < 5; i++)
var t = SomeFunction();

will result in a compile error CS1023: “Embedded statement cannot be a declaration or labeled statement”?

Before you ask why you would even need it (the reason, in my case, is that the analyser doesn’t like function results being ignored), let me point out that this code works just fine:

for(int i = 0; i < 5; i++)
{
var t = SomeFunction();
}

To be clear, this issue has nothing to do with the use of var. For instance, using:

for(int i = 0; i < 5; i++)
string t = SomeFunction();

will also lead to the same error.

--

--

Guriy Samarin
Guriy Samarin

Written by Guriy Samarin

Software developer at Amazon. Web (mostly backend) development now. My stack — .NET (APS.NET Core MVC).

No responses yet