views:

3894

answers:

5

I'm trying generics for the first time and am having a problem.

I have a dll that sends messages in batches

  • there is a "Message" class and a "Batch" class in that dll

  • on the batch class, I have some public properties

  • on of the batch class's public properties is a property called "Messages" which is a list of the "Message" class as follows:

     public List<Message> Messages {get;set;}
    

Method 1

I then have a test exe where I want to set the properties on the "Batch" class as follows:

Batch myBatch = new Batch()
myBatch.Messages.Add(
  new MyNameSpace.Message(txtToAddress.Text, txtMessage.Text));

When I run the app, I get:

"Object reference not set to an instance of an object."

Method 2

After playing around a bit, I see that I can successfully do the following in the test exe:

List<MyNameSpace.Message> myMessages = new List<MyNameSpace.Message>();
myBatch.Messages.Add(
 new MyNameSpace.Message(txtToAddress.Text, txtMessage.Text));
myBatch.Messages = myMessages;

I'd like to get it working in the first way because other programmers will be using the dll and it seems more intutive to use the first approach.

What am I missing to get the first method to work?

+6  A: 

Normally, collections are initialized by the parent object:

public List<Message> Messages {get; private set;}

public Batch() { // constructor
    Messages = new List<Message>();
}

Now it should work as expected. Note that if you are using XmlSerializer you'll need to keep the public set too...

In some ways, the long-hand property code is easier here:

private List<Message> messages = new List<Message>();
public List<Message> Messages { get {return messages; } }

(no messing with constructors, etc)

Marc Gravell
+1  A: 

You need to instantiate your list first.

Add this to your contstructor

Messages = new List<Message>();
Eoin Campbell
+1  A: 
Batch myBatch = new Batch()
myBatch.Messages.Add(

After creating a new batchthe Messages List is probably not created yet. Create the List in the constructor of Batch.

PoweRoy
+1  A: 

In the constructor of the Batch class, create a list for the Messages property:

public Batch() {
   Messages = new List<Messages>();
}
Guffa
+1  A: 

Your Batch class would have to be responsible for creating an instance of the List probably in the constructor would be the best place.

Tim Jarvis