|
-
January 19th, 2011, 06:26 PM
#1
Using custom object arrays
I use the latest .NET framework. I've hunted high and low for a full solution to this. Coming from a C/C++ background, the below should print out "50" twice, but unfortunately, the second 'Dog' one crashes.
One 'solution' seems to involve 'further instantiation' by using the code: d[10] = new dog(); just before d[10].n=50, but then sounds painful because then if I want access to all 1000 elements, I'll need to use a For loop to instantiate each one individually. Also that wouldn't explain why int gets away with it, but dog doesn't.
Any thoughts? The error encountered is: "NullReferenceException was unhandled".
(On a vaguely related note, can I allocate structs on the heap?)
Code:
using System;
class dog { public int n; }
class Program
{
static void CreateInt() {
int[] d = new int[1000];
d[10] = 50; Console.WriteLine(d[10]);
}
static void CreateDog() {
dog[] d = new dog[1000];
d[10].n = 50;
Console.WriteLine(d[10].n);
}
static void Main(string[] args)
{
CreateInt();
CreateDog();
Console.ReadLine();
}
}
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|