Can you do
array['Name'];
In C#
Rather than:
array[0];
I know you can do that in PHP but is there an equivelent for C#, although im thinking highley unlikely :(
Array elements are accessed by using an integer index. Array index starts with 0 and goes till size of array minus 1. Name of the array is also a pointer to the first element of array.
Arrays in C/C++. An array in C or C++ is a collection of items stored at contiguous memory locations and elements can be accessed randomly using indices of an array. They are used to store similar type of elements as in the data type must be the same for all elements.
Advantages of an Array in C/C++: 1 Random access of elements using array index. 2 Use of less line of code as it creates a single array of multiple elements. 3 Easy access to all the elements. 4 Traversal through the array becomes easy using a single loop. 5 Sorting becomes easy as it can be accomplished by writing less line of code. More ...
When an array in C is passed to a function, only the address of the array’s first element is passed to the function. And being contiguous in nature, the whole array can be accessed by the function using the address of the first element. We can pass a single array element to a function as its argument.
Arrays don't work like that in C#, but you can add an indexer property to any class:
class MyClass
{
public string this[string key]
{
get { return GetValue(key); }
set { SetValue(key, value); }
}
}
Then you can write the type of statements you ask against this:
MyClass c = new MyClass();
c["Name"] = "Bob";
This is how string-based indexed access to Dictionary<TKey, TValue>
, NameValueCollection
and similar classes are implemented. You can implement multiple indexers as well, for example, one for the index and one for the name, you just add another property as above with a different parameter type.
Several built-in framework classes already have these indexers, including:
SortedList<TKey, TValue>
Dictionary<TKey, TValue>
SortedDictionary<TKey, TValue>
NameValueCollection
Lookup<TKey, TValue>
(in System.Linq
)...and more. These are all designed for slightly different purposes, so you'll want to read up on each and see which one's appropriate for your requirement.
Dictionary<string, whatyouwanttostorehere> myDic =
new Dictionary<string, whatyouwanttostorehere>();
myDic.Add("Name", instanceOfWhatIWantToStore);
myDic["Name"];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With