Click to Rate and Give Feedback
MSDN
MSDN Library
Visual Studio 2008
Visual Studio
Visual C#
C# Reference
C# Operators
 [] Operator
Collapse All/Expand All Collapse All
This page is specific to
Microsoft Visual Studio 2008/.NET Framework 3.5

Other versions are also available for the following:
C# Language Reference
[] Operator (C# Reference)

Square brackets ([]) are used for arrays, indexers, and attributes. They can also be used with pointers.

An array type is a type followed by []:

C#
int[] fib; // fib is of type int[], "array of int".
fib = new int[100]; // Create a 100-element int array.

To access an element of an array, the index of the desired element is enclosed in brackets:

C#
fib[0] = fib[1] = 1;
for (int i = 2; i < 100; ++i) fib[i] = fib[i - 1] + fib[i - 2];

An exception is thrown if an array index is out of range.

The array indexing operator cannot be overloaded; however, types can define indexers, and properties that take one or more parameters. Indexer parameters are enclosed in square brackets, just like array indexes, but indexer parameters can be declared to be of any type, unlike array indexes, which must be integral.

For example, the .NET Framework defines a Hashtable type that associates keys and values of arbitrary type:

C#
System.Collections.Hashtable h = new System.Collections.Hashtable();
h["a"] = 123; // Note: using a string as the index.

Square brackets are also used to specify Attributes (C# Programming Guide):

C#
// using System.Diagnostics;
[Conditional("DEBUG")] 
void TraceMethod() {}

You can use square brackets to index off a pointer:

C#
unsafe void M()
{
    int[] nums = {0,1,2,3,4,5};
    fixed ( int* p = nums )
    {
        p[0] = p[1] = 1;
        for( int i=2; i<100; ++i ) p[i] = p[i-1] + p[i-2];
    }
}

No bounds checking is performed.

For more information, see the following sections in the C# Language Specification:

  • 1.6.7.5 Operators

  • 7.2 Operators

Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
Processing
© 2009 Microsoft Corporation. All rights reserved. Terms of Use | Trademarks | Privacy Statement | Site Feedback
Page view tracker