IList<> object initialization problem

L

Lonifasiko

I've got this in my code, that is, we're inside a class called Patient,
so a Patient can have Appointments:


private IList<Appointment> _appointments = null;


public IList<Appointment> Appointments
{
get
{
if (_appointments == null)
{
RetrievePatientAppointments();
}
return _appointments;
}
set
{
_appointments = value;
}
}

The "RetrievePatientAppointments" method queries database, obtains
records and tries to add Appointment objects in a foreach bucle. The
pain is that when it is bound to add an Appointment, fails, because it
is null (The initialization of the IList is to null if you see).

How could I avoid IList being null? How to initialize it?
 
N

Nick Parker (C# MVP)

You can initialize it to a List<T>, so for you example:

private IList<Appointment> _appointments = new List<Appointment>();
 
B

Bill Butler

public IList<Appointment> Appointments
{
get
{
if (_appointments == null)
{
RetrievePatientAppointments();
}
return _appointments;
}
set
{
_appointments = value;
}
}
<snip>

It is , in general, a bad idea to make database queries in properties.
Properties are better when the data is already on hand or easily accessible.
This case look like a GetAppointments() Method might be a better fit.

Bill
 
J

James Curran

Nick Parker (C# MVP) said:
You can initialize it to a List<T>, so for you example:

private IList<Appointment> _appointments = new List<Appointment>();

Umm... You wouldn't want to do that in the definition, as that way, it
would never be null, and RetrievePatientAppointments() will never be called.
Better to do it inside RetrievePatientAppointments(). Best would be to
initialize a local variable inside RetrievePatientAppointments(), and return
that List.

--
Truth,
James Curran
[erstwhile VC++ MVP]

Home: www.noveltheory.com Work: www.njtheater.com
Blog: www.honestillusion.com Day Job: www.partsearch.com
 
I

Ignacio Machin \( .NET/ C# MVP \)

Hi,

You have to initialize _appointments inside RetrievePatientAppointments :

void RetrievePatientAppointments()
{
_appointments = new List<AppointMeint>();
//query the db
}


cheers,
 
L

Lonifasiko

Sorry guys, I did not notice I could do List<Appointment> _appointments
= new List<Appointment>()

I was trying to create a "new interface".......simply a bad programming
day.......

Thanks folks.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top