© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•3y ago•
18 replies
DiMiaN

✅ How to add data to a list that is outside of Main()?

using System.Collections.Generic;
internal class Program
{
    public static void insertData(string animal, int amount)
    {
        var list = new List<KeyValuePair<string, int>>();
        list.Add(new KeyValuePair<string, int>(animal, amount));
    }
    private static void Main(string[] args)
    {
        insertData("Dog", 4);
        insertData("Cat", 12);

        foreach(var element in list)
        {
            Console.WriteLine(element);
        }
    }
}
using System.Collections.Generic;
internal class Program
{
    public static void insertData(string animal, int amount)
    {
        var list = new List<KeyValuePair<string, int>>();
        list.Add(new KeyValuePair<string, int>(animal, amount));
    }
    private static void Main(string[] args)
    {
        insertData("Dog", 4);
        insertData("Cat", 12);

        foreach(var element in list)
        {
            Console.WriteLine(element);
        }
    }
}

I know there are some errors but I can't figure out how to solve this. Also when calling the insertData the list will be resetted every new call?
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

WPF how to add data from 2 list entries to a different window that uses a CustomContol
C#CC# / help
2y ago
How to set the whole application culture outside of main()?
C#CC# / help
2y ago
❔ Using text file to add data into a list
C#CC# / help
3y ago
❔ How to make a list of tuples that hold references?
C#CC# / help
3y ago