Click to See Complete Forum and Search --> : C# array - Any explanation for this?


savagerx
February 7th, 2003, 11:45 AM
Swordman[] obj = new Swordman[3];

In other languages, memory is allocated but in C#, no.

compiler msg:
Unhandled Exception: System.NullReferenceException: Object reference not set to
an instance of an object.
at Swordman.Main()

MSIL:
.method private hidebysig static void Main() cil managed
{
.entrypoint
// Code size 8 (0x8)
.maxstack 1
.locals init (class Robot[] V_0)
IL_0000: ldc.i4.3 //loads System.Int32 (value 4)
IL_0001: newarr Swordman //creates new array
IL_0006: stloc.0 //pops into first var
IL_0007: ret //end...
} // end of method Swordman::Main

But when I used,
Swordman[] obj = new Swordman[3];
obj[0] = new Swordman();

compiler okay.

MSIL:
.method private hidebysig static void Main() cil managed
{
.entrypoint
// Code size 16 (0x10)
.maxstack 3
.locals init (class Robot[] V_0)
IL_0000: ldc.i4.3
IL_0001: newarr Swordman
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: ldc.i4.0
IL_0009: newobj instance void Swordman::.ctor() //creates new object.
IL_000e: stelem.ref
IL_000f: ret
} // end of method Swordman::Main

Therefore, doesn't the first statement allocate memory?

pareshgh
February 7th, 2003, 12:02 PM
it actually depends upon wether its an object or datatype...

for instance

int [5]data = new int[5]

and the next statement can be
data[0] = 10;

but if

Swordman[] obj = new Swordman[3];

then
for ( int i=0; i<3; i++)
Swordman[i] = new Swordman();
here invokes the constructor and initializes.the object....

Paresh

savagerx
February 8th, 2003, 04:28 PM
hmmzzz... thanks pal.

pareshgh
February 10th, 2003, 10:45 AM
actually there isn't basic datatype thing in C# so it makes more sense to make an object of data type and treat as the way objects are treated.
C++ was a diff. in case of datatypes...


Paresh