ArrayList in a struct

  • Thread starter Thread starter Michael C
  • Start date Start date
M

Michael C

Is it possible to use an ArrayList inside a struct? I keep running into a
null reference exception when I try to Add to the ArrayList in the struct,
and it won't let me initialize the ArrayList in the struct. Any ideas?

Thanks,
Michael C.
 
Michael,

Guess, its not possible to keep ArrayList inside a struct. Its becoz

1.struct is a value type and ArrayList is a class which is a reference type
2. You can have struct inside a class, but not the reverse.

In this case, you are trying to keep a class object (reference object)
inside the struct (value type). This will throw an exception.

Shak.
 
Michael,
Is it possible to use an ArrayList inside a struct?

Yes. eg :

public struct SR
{
public int kk;
public ArrayList list; // XXX
}

private void button1_Click(object sender, System.EventArgs e)
{
SR sr = new SR();
sr.list = new ArrayList();
sr.list.Add("this should work");
MessageBox.Show(sr.list[0].ToString());
}

Limitations :
- you can't initialize the ArrayList at XXX. eg. public ArrayList list =
new ArrayList() won't compile.
- can't create your own parameterless constructors for structs. Even if you
create a constructor
with parameters and initialize the ArrayList there, you can't stop the user
from using the
default (parameterless) constructor, since there's no way of overriding it.

HTH,
Stephen
 
Shakir Hussain said:
Guess, its not possible to keep ArrayList inside a struct. Its becoz

Yes it is.
1.struct is a value type and ArrayList is a class which is a reference type
2. You can have struct inside a class, but not the reverse.

Yes you can.
In this case, you are trying to keep a class object (reference object)
inside the struct (value type). This will throw an exception.

No it won't.

Here's an example program.

using System;
using System.Collections;

struct Container
{
ArrayList list;

public Container(params object[] members)
{
list = new ArrayList();
foreach (object o in members)
{
list.Add(o);
}
}

public Container (Container container)
{
this.list = container.list;
}

public void Display()
{
foreach (object o in list)
{
Console.WriteLine (o);
}
}
}

class Test
{
static void Main(string[] args)
{
Container c = new Container(args);
Container other = new Container(c);
other.Display();
}
}
 
Back
Top