0

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?

asked Jul 13, 2018 at 13:21
3
  • 4
    As it stands, your method takes a 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? Commented Jul 13, 2018 at 13:28
  • 1
    If you did create a method - the whole array would not be sent to the method, just a reference to the array - so it wouldn't be any different passing a single element array to passing a 1000000 element array. Commented Jul 13, 2018 at 13:42
  • Is an extension method acceptable? Commented Jul 13, 2018 at 13:44

2 Answers 2

1

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);
answered Jul 13, 2018 at 13:31

1 Comment

And this ends up receiving the full array.
0

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;
}
answered Jul 13, 2018 at 13:27

3 Comments

thanks but i want a method to do that for me and i cant access the array if i send an element of that array to the method
I think what OP wants is for the nextItem() method to increment index & wrap if longer than the length of the array.
@Fake Updated it with a method. You'd have to pass the array length too. Hope it helps!

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.