The name ‘str’ does not exist in the current context

You’ve almost certainly declared the variable in a method (i.e. as a local variable), instead of directly in the class itself (as an instance variable). For example:

// Wrong
class Bad
{
    void Method1()
    {
        List<string> str = new List<string>();
    }

    void Method2()
    {
        foreach (string item in str)
        {
            ...
        }
    }
}

// Right
class Good
{
    private List<string> str = new List<string>();

    void Method1()
    {
        str = CreateSomeOtherList();
    }

    void Method2()
    {
        foreach (string item in str)
        {
            ...
        }
    }
}

As a side-note: if you’re very new to C#, I would strongly recommend that you stop working on Silverlight temporarily, and write some console apps just to get you going, and to teach you the basics. That way you can focus on C# as a language and the core framework types (text, numbers, collections, I/O for example) and then start coding GUIs later. GUI programming often involves learning a lot more things (threading, XAML, binding etc) and trying to learn everything in one go just makes things harder.

Leave a Comment