C# indexer Simple Example

CSharp · Console

/Program.cs

using System;

public class Program
{
	public static void Main()
	{
		var foo = new Foo();
		// access a value    
		string berlin = foo[2];
		// assign a value
		foo[0] = "Rome";
		
		Console.WriteLine(foo[0]);
	}
}

class Foo
{
	private string[] cities = new[]
	{
	"Paris", "London", "Berlin"
	};
	
	public string this[int index]
	{
		get
		{
			return cities[index];
		}

		set
		{
			cities[index] = value;
		}
	}
}
;