Click here to Skip to main content
15,891,372 members
Articles / Programming Languages / C#
Tip/Trick

The NameValueCollection quick example

Rate me:
Please Sign up or sign in to vote.
4.00/5 (1 vote)
23 Apr 2013CPOL 30.3K   2   1
A quick example on how to use the NameValueCollection class

Introduction

One of the most common questions I've been asked is "How can I make a collection that allows me to enter either a key or an index to pull a value?" (well, usually it's formed more like "I want to build a property in my class that works just like the .Items property in x class", "How can I make a collection that works like AppSettings["key"], or some other specific but related question)

I've been asked this question often enough that I'm just going to put together a quick tip / example so people can reference it whenever they need to.

Background 

You'll need to reference the System.Collections.Specialized namespace and use the NameValueCollection class

Using the code 

Below is a quick console application that creates a NameValueCollection variable, Populates it with data, and then displays one of the values to the console. Very simple example code that you can reference and expand upon in your own projects.

C#
using System;
using System.Collections.Specialized;

namespace ConsoleApplication1
{
  /// <summary>
  /// An incredibly simple demonstration of
  /// NameValueCollection
  /// </summary>
  class Program
  {
    static void Main(string[] args)
    {
      // Say we want a simple string collection. Similar to AppSettings or the like.
      
      // make a collection
      NameValueCollection tags = new NameValueCollection();
      // quick loop to populate it with some demo values.
      for (int i = 1; i <= 10; i++)
      { 
        tags.Add(string.Format("tag{0}",i.ToString()),string.Format("The value of tag{0}",i.ToString()));
      }
      // in this case we know there is an index of tag2 so we'll hard
      // code for the demo
      Console.WriteLine(tags["tag2"]);
      Console.ReadLine();

    }
  }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
United States United States
Developing software since 1995, starting out with Borland Turbo C++ 3 & Motorolla Assembly.
Eventually learning several different languages such as
Pascal/Delphi,Basic, Visual Basic,FoxPro, ASP, PHP, and Perl.

Currently using the .net framework for most development task.

Hobbies include underwater robotics, and electronics.

George's current language of choice is C#.

Comments and Discussions

 
GeneralMy vote of 4 Pin
Jason Down1-May-13 3:25
Jason Down1-May-13 3:25 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.