C# .NET - Null exception - Asked By mostafa hamdy on 14-Sep-10 04:59 AM

Hello all
I have some list of objects , and when this list is null or its count is =0 I want to create some thing , but when the list is null I get null reference exception the code is as the following:

List<Registry> lstInstalledProducts = new List<Registry>();

lstInstalledProducts =objInstalledProducts.GetInstalledProducts();

if (lstInstalledProducts.Count==0 ||lstInstalledProducts==null)

{

//do some thing
}

please if any body get what's the error and can help me in solving it please send me or tell me about some url may help me in solving it
regards
Mostafa
Sagar P replied to mostafa hamdy on 14-Sep-10 05:03 AM
Actaully if list is null then you can't use any of its method. And you are using Count and because of that it is throwing error. You have to seperate these conditions like;

lstInstalledProducts =objInstalledProducts.GetInstalledProducts();


if (lstInstalledProducts==null)

{

//do some thing
}
else if(lstInstalledProducts.Count==0)
{
//do some thing
}

You can use function and call that function in both if and else.....
Try this.
Sasha Kotlo replied to mostafa hamdy on 14-Sep-10 05:12 AM
Actually you don't need to do it the way Sujit told you. Much easier and faster is implementing it in 1 condition like this:

if(lstInstalledProducts != null && lstInstalledProducts.Count > 0)
{
// list has entries do whatever necessary in here
}
else
{
// list is null or empty
}

Regards.