user12831231
user12831231

Reputation: 11

How to use a list in functions outside main?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Lazo
{
    class Program
    {
        List<string> L = new List<string>();
        static void Main(string[] args)
        {
            //List<string> L = new List<string>();
            L.Add("L");
            L.Add("A");
            L.Add("Z");
            L.Add("O");

            izbrisiElement("test");
        }

        static void izbrisiElement(string element_brisi)
        {
            for (int i = 0; i < L.Count - 1; i++)
            {
                if (L[i] == element_brisi)
                {
                    //do something
                }
            }
        }
    }
}

I want to use the list created in main in other functions outside main. I have tried inside main and outside main, but none works. I'm not exactly sure where my mistake is. Could anyone help me out?

Upvotes: 0

Views: 1214

Answers (2)

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101701

Main method is static, it means it doesn't belong to any instance, but you are declaring your list as an instance field.So when you access it in a method it means you are trying to access the member of the current instance in other words: this.L, but this doesn't exist in the static context.

You need to make it static:

static List<string> L = new List<string>();

Upvotes: 3

Christos
Christos

Reputation: 53958

You should declare it as static:

static List<string> L = new List<string>();

in order to be used from your static methods.

Upvotes: 1

Related Questions