0

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.

6
  • 1
    Your AmountData object in your list is possibly NULL. Check it Commented Jun 21, 2010 at 11:10
  • 2
    Are you positive that Amount_Details isn't returning null? Commented Jun 21, 2010 at 11:10
  • 1
    If it was returning null, then if(d.capacity...) should throw the exception Commented Jun 21, 2010 at 11:15
  • @ck, maybe that's where the exception is thrown. Commented Jun 21, 2010 at 11:17
  • @user372066 are you sure exception is thrown at foreach line? Commented Jun 21, 2010 at 11:28

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

4

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>();

Comments

1

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.

4 Comments

Surely that would crash when he called capacity on the null reference on the next line, not at the foreach? (agreed with the advice though, never return null collections!)
hm, you are right. Either it has to occur in the conditional or in the foreach block (because either d or temp are null) but in the foreach-decleration? hm.
Is there any way that the result of Amount_Details could be a subclass of List<> that has overridden the GetEnumerator() method? I wouldn't have thought that was possible, but I can't think what else happens on the foreach line.
This could be possible. But without a call stack it is impossible to say.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.