CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Apr 2008
    Posts
    26

    [RESOLVED] NullReferenceException where there shouldn't be one

    I've created a static function inside of a class, and then tried to create an array of instances of said class inside the static function and during run time a NullReferenceException is thrown. I am not a seasoned C# coder, so I'm sure I'm missing something obvious. Please take a look at the code below
    Code:
    public class X
    {
        public int id = 1;
        public static void run()
        {
            X[] newX = new X[2];
            newX[0].id.ToString();
        }
    }
    // Note: This code is provided simply as an example, I realize it has no significant purpose
    Then when run() is executed the exception is thrown. I'm on a tight deadline so any help would be greatly appreciated. I'll find an alternate way to accomplish what I want for now, but I'd really like to know what I was doing wrong here.

    Thankyou

  2. #2
    Join Date
    Apr 2008
    Posts
    26

    Re: NullReferenceException where there shouldn't be one

    I feel rather silly, immediately after I posted this I realized what I was doing wrong. I was creating a new array but the array was not being filled with constructed instances of X. The following code runs smoothly
    Code:
    public class X
    {
        public int id = 1;
        public static void run()
        {
            X[] newX = new X[2];
            newX[0] = new X();
            newX[0].id.ToString();
        }
    }
    // Note: This code is provided simply as an example, I realize it has no significant purpose
    Sorry about that. If someone could delete this I'd appreciate it. Though I suppose it doesn't matter.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured