0

I've got simple class, something like this:

public class myClass
{
    public static readonly string[] stringArray= { "one", "two" };
    private string myString;

    public myClass (int _index)
    {
       if(_index > (stringArray.Length - 1) || _index < 0)
       {
           throw new IndexOutOfRangeException("Bad index.");
       }
       else
       {
           myString = stringArray[_index];
       }
    }

}

I'm running simple constructor: myClass example = myClass(5); and I've got error. It shouldn't leave constructor without trying create new object?

I don't understand how throw works there.


Edit: Sorry, I made a mistake. There should be stringArray.Length -1 in if section.

user3692826
  • 107
  • 1
  • 11
  • This is not a duplicate. The OP has a type in his code and he needs help. – Black Frog Dec 04 '14 at 18:34
  • Do you not understand why your exception is being thrown, or why throwing an exception in the constructor will cause the object to not be initialized? – juharr Dec 04 '14 at 18:37
  • I just want something like that: myClass example = myClass(1); -> It's ok, I've my object myClass example = myClass(5); -> Write error in Console. – user3692826 Dec 04 '14 at 18:38
  • What is the question here: why myClass example = myClass(5); throws an expcetion ? – mybirthname Dec 04 '14 at 18:43

3 Answers3

3

myString is null, so you are getting a NullReferenceException when you access the Length property.

My guess is that you want:

if(_index > (stringArray.Length - 1) || _index < 0)
John Koerner
  • 37,428
  • 8
  • 84
  • 134
1

Because you are passing 5 as the _index to your constructor the following if condition will be true

if(_index > (stringArray.Length - 1) || _index < 0)

because the length of the array is 2 an 5 > 1. This causes the code to throw the IndexOutOfRangeException which stops the constructor from returning an instance of the object. Additionally if you do not have a try-catch around the new myClass(5) then the exception will bubble up and cause your running application to crash.

juharr
  • 31,741
  • 4
  • 58
  • 93
0

You have a typo in your code. You need to get the length of the array not the string.

The line of code should:

 if(_index > (stringArray.Length - 1) || _index < 0)
Black Frog
  • 11,595
  • 1
  • 35
  • 66