Index out of bounds

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Madmartigan
    New Member
    • Dec 2006
    • 23

    Index out of bounds

    Hi

    I'd like to know how to inlcude a check to make sure the index requested is not out of bounds in C#.

    In the following code I have created an array to store ten numbers at most. The array must be accessible using an Indexer. In the Indexer I would like to include the check.


    Code:
    using System; 
     class Numbers {
    
     private int[] nums = new int[10]; 
     public int this [uint index] {
    
       get {
                    // can I add a check here and if so what is the syntax?
        	return nums[index];
        }
        set {
     	// will I need it here too?
          	lots[index] = value; 
        }
     
      }
    
    
    static void Main() {
        Numbers num = new Numbers(); 
        num[0] = 1; 
        num[1] = 23; 
        num[2] = 5; 
        num[3] = 5;
        num[4] = 24;
        num[5] = 5;
        num[6] = 5;
        num[7] = 67;
        num[8] = 90;
        num[9] = 11;
    
    
        for (uint i = 0; i < 10; i++) {
    		Console.WriteLine("The numbers " + num[i]);
    
    
       }
     } 
     	
     }
    Thanks for your help.

    M
  • Plater
    Recognized Expert Expert
    • Apr 2007
    • 7872

    #2
    All the arrays have a .Length property that tells how many there are.
    In your case:
    Code:
    nums.Length
    It will return a 10. Your index should be allowed 0-9 (assuming C#)
    So index <nums.Length

    Comment

    Working...