In python, I've gotten into the habit of using variables inside a for loop outside of its "scope". For example:
l = ["one", "two", "three"]
for item in l:
if item == "one":
j = item
print(j)
You can't quite do this in C#. Here are the several attempts I made:
First attempt
I declare a variable j
of type string
, assign the selected item to it inside the foreach
loop scope and then refer back to it once I exit the foreach
loop scope:
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<string> l = new List<string> { "one", "two", "three" };
string j;
foreach (string item in l)
{
if (item == "one")
{
j = item;
}
}
Console.WriteLine(j);
}
}
The compiler throws an error:
Microsoft (R) Visual C# Compiler version 4.2.0-4.22252.24 (47cdc16a) Copyright (C) Microsoft Corporation. All rights reserved.
test.cs(19,27): error CS0165: Use of unassigned local variable 'j'
Second attempt
Moving the declaration inside the foreach
is also no good, because the variable is not recognized outside of the scope at all:
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<string> l = new List<string> { "one", "two", "three" };
foreach (string item in l)
{
string j;
if (item == "one")
{
j = item;
}
}
Console.WriteLine(j);
}
}
The compiler throws the following error:
Microsoft (R) Visual C# Compiler version 4.2.0-4.22252.24 (47cdc16a) Copyright (C) Microsoft Corporation. All rights reserved.
test.cs(20,27): error CS0103: The name 'j' does not exist in the current context
Third attempt:
Moving the declaration in the innermost scope and assigning the value to the variable results in a similar problem as the second attempt:
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<string> l = new List<string> { "one", "two", "three" };
foreach (string item in l)
{
if (item == "one")
{
string j = item;
}
}
Console.WriteLine(j);
}
}
The compiler complains because at line 19 the variable j
is not recognized.
Microsoft (R) Visual C# Compiler version 4.2.0-4.22252.24 (47cdc16a) Copyright (C) Microsoft Corporation. All rights reserved.
test.cs(19,27): error CS0103: The name 'j' does not exist in the current context
The solution
One possible solution is as follows:
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<string> l = new List<string> { "one", "two", "three" };
string j = "test";
foreach (string item in l)
{
if (item == "one")
{
j = item;
}
}
Console.WriteLine(j);
}
}
But I find this to be quite ugly and lacking robustness, because I have to assign some dummy value to j
. For instance, perhaps the string "test"
is recognized by other parts of my program and would make it behave in unexpected ways.
Question
Is there an elegant alternative to achieve this kind of behavior in C#, or am I missing something?