Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use Square Brackets to pull a value from a class

Tags:

c#

I have a class that has the variable "Magic". This is a 4 char string. Can I do something like this in C#?

string offset = chunkList["_blf"].offset;

*Assume that "chunkList" is an IList/List of "chunk" objects.

like image 313
Alexander Forbes-Reed Avatar asked Jul 23 '12 14:07

Alexander Forbes-Reed


People also ask

What do square brackets do in CSS?

The square brackets are used as an attribute selector, to select all elements that have a certain attribute value. In other words, they detect attribute presence.

What is square brackets in Python?

The indexing operator (Python uses square brackets to enclose the index) selects a single character from a string. The characters are accessed by their position or index value. For example, in the string shown below, the 14 characters are indexed left to right from postion 0 to position 13.

What does bracket mean in HTML?

You can see that HTML contains pieces enclosed in angle brackets (' < ' and ' > '), which are also known as the less-than and greater-than symbols. Each of these angle-bracket-enclosed pieces, called a tag, does not appear to the user, but rather gives information about the page's structure.


2 Answers

You could use something like this:

string offset = chunkList.Find(x => x.Magic == "_blf").offset;

Better is to check if Find retuns null:

Chunk chunk = chunkList.Find(x => x.Magic == "_blf");
if (chunk != null)
    offset = chunk.offset;
like image 42
Carsten Schütte Avatar answered Sep 17 '22 18:09

Carsten Schütte


Yes, you can create an indexer on your class:

public string this[string s]
{
    get
    {
        // retrieve value
    }
    set
    {
        // set value
    }
}
like image 54
Joey Avatar answered Sep 19 '22 18:09

Joey