开发者

C# List + Object reference not set to an instance of an object

I have this code in C#. It is returning "Object reference not set to an instance of an object" exception.

Code:

    public decimal Calculate(String id)
    {
        decimal Total=0;
        AmountDataDB getData=new AmountDataDB();
        List<AmountData> d = new List<AmountData>();
        d = getData.Amount_Details(id);
        if (d.Capacity != 0)
        {
            foreach (AmountData temp in d)//NullReference exception occurs here
            {
                Total += temp.Amount;
          开发者_如何转开发  }

        }
        return Total;
    }

Here, AmountDataDB and AmountData are two classes. Amount_Details returns a list of type AmountData.


Non-answer (advice):

Please, please x 100000, dont ever write code like:

List<AmountData> d = new List<AmountData>();
d = getData.Amount_Details(id);

It is totally pointless creating a new list only to have it overwritten in the next line.


You could use the null-coalescing operator to ensure that the d variable is never null:

List<AmountData> d = getData.Amount_Details(id) ?? new List<AmountData>();


getData.Amount_Details(id); returns null, probably because there are no records for that particular id. You probably should change the behaviour of Amount_Details() to return an empty list instead of null if there are no records.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜