Rookie C# problem
I am a rookie to C# and here is my question
class myClass
{
int start;
int end;
.......
}
class program
{
public void main()
{
myClass[] a= new myClass[10];
for (int i = 1; i < a.length; i++)
{
myClass b = new myClass();
开发者_如何学运维 a[i] = b;
a[i].start = 1;
... (keep populating)
...
}
console.writeline(a[1].start) // NO PROBLEM WITH THIS LINE, THE VALUE WAS OUTPUTED
subMethod(a);
}
public void subMethod(myClass[] a)
{
console.write(a[1].start); // NO PROBLEM WITH THIS LINE, OUTPUT NORMALLY
for (int i = 1; i < a.length, i++)
{
int h = a[i].start; ????? OBJECT NOT INSTANTIATED
}
}
}
The error is as indicated above and I have difficulty to understand it. Anyone can help me out. Thanks in advance
The problem seems to be in the code that you haven't posted.
myClass[] a= new myClass[10];
// (populate this array)
I've no idea what you have written there but it clearly isn't working. It should be this:
myClass[] a = new myClass[10];
for (int i = 0; i < a.Length; i++)
{
a[i] = new myClass();
}
- The code you posted won't compile. Please copy + paste the actual code - don't try to write it from memory.
- You should notice that the first index in an array is 0, not 1.
- I'd also suggest that you read the Microsoft naming guidelines, for example class names should be in Pascal case.
You've instantiated an array but new need to instantiate each object in the array. You are not showing how you do that bit in the example above.
Please post code that compiles. The error is probably in your transcribing of the code, because this code works perfectly fine:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace RandomArrayTest
{
class MyClass
{
public int start;
}
class Program
{
static void Main(string[] args)
{
MyClass[] a = new MyClass[10];
for(int i=1; i<a.Length; i++)
{
MyClass b = new MyClass();
a[i] = b;
a[i].start = 1;
}
MyFunction(a);
}
static void MyFunction(MyClass[] a)
{
for (int i = 1; i < a.Length; i++)
{
int h = a[i].start;
Console.WriteLine(h);
}
}
}
}
精彩评论