i wanted to make my normal array to a circular array by declaring a method for example this can be my char array:
char[] c = Console.ReadLine().ToCharArray();
i wanted to declare e method that i can use like this:
char c1=c[3].nextItem();
and if my array length was bigger than 4 it returns c[4] else it returns c[0] is there any way to declare a method like nextItem() without sending whole array to the method?
2 Answers 2
If you use, char c1=c[3].nextItem();
, the method starts from the char
, not from the array and you don't have the knowledge about the array.
A proposition to create a custom method for the array char
:
public static class MyExtensions
{
public static char nextItem(this char[] chars, int index)
{
//index start from 0
// my array length was bigger than 4 it returns c[4]
if(chars.length() > index+1)
return chars[index+1];
else
//it returns c[0]
return chars.Length() > 0 ? chars[0] : '';
}
}
And the calling:
char[] c = Console.ReadLine().ToCharArray();
var singleChar = c.nextItem(3);
1 Comment
Something like:
char c1 = (index < c.Length - 1) ? c[index].nextItem() : c[0];
If you want a method, you could just return the index:
char c1 = c[CheckIndex(index, c.Length())];
public static int CheckIndex(int index, int length)
{
return index < length - 1 ? index : 0;
}
char
as an argument (assuming it's an extension method), so in fact it has no idea there is an array. So no, at some point, the whole array must be passed to a helper method. Maybe the question is, why is passing the whole thing a problem at all?