Henrik Pettersson
Henrik Pettersson

Reputation: 41

Beginner with C#, help explaining a code snippet

First of I need to be clear on the fact that I'm new to C#. I believe in a practical approach so I've mixed my reading with practical examples. I also enjoy reading code and trying to really understand it. However this one thing keeps me puzzled.

I've checked my books and the internet but I don't really know what to search for in order to find it.

Anyway here's the code.

for (int t = 0; t < res.Length / 2; t++)
{
    if (res[t] != res[res.Length -t -1]) Initial = false;
}

res isn't declared as an array earlier in the code, yet it's made res[t] in the if statement. I read something about "indexing" elsewhere but didn't get much further so now I'm asking you for help explaining this little trick for me. Hopefully the explanation wont blow my mind to pieces.

Thanks in advance.

Upvotes: 0

Views: 208

Answers (4)

Andrej B.
Andrej B.

Reputation: 170

This code set Initial to false if ret is not palindrome. for example:

var res = new int[] {1,2,3,4,5, 6}; // not palindrome
var res1 = new int[] {1,2,3,3,2, 1}; // palindrome
var resString = "notpalindrome";
var resString1 = "asdfgfdsa"; // palindrome

Upvotes: 2

dcastro
dcastro

Reputation: 68740

In c#, when you're building your classes, you can make them "indexable". This means that you can access the underlying data by means of indexing, just like you would do with an array.

Say you have a DuckCollection class, which internally stores a Duck[] duckArray array. Now, you want users of your DuckCollection class to be able to do var duck = duckCollection[0] instead of var duck = duckCollection.duckArray[0].

You'd do it like this:

public class DuckCollection
{
    Duck[] duckArray;

    public Duck this[int index]    // Indexer declaration
    {
        return duckArray[index];
    }


}

Many classes in C# implement this kind of behaviour, like strings, lists, etc. That's why you can access individual elements on strings (i.e., chars) as if it was an array.

More info on indexers: http://msdn.microsoft.com/en-us/library/2549tw02.aspx

Upvotes: 0

JNYRanger
JNYRanger

Reputation: 7097

Strings in C# are actually arrays of characters. This is why you are able to locate a single character within the string using the [] with an index value.

Upvotes: 2

Karel Frajt&#225;k
Karel Frajt&#225;k

Reputation: 4489

Use debugger to see what's going on.

My guess it is comparing string characters (res, string "behaves" like array of char) at positions (L is length of the string) [0, L-1], [1, L-2], [2, L-3], ... and setting Initial to false when they are not the same.

Upvotes: 0

Related Questions