Adding items in order gives NullReferenceException (WooCommerce, in C# and using WooCommerce.NET addin.

pink glitter
pink glitter used Ask the Experts™
on
I am trying to use this code for making an order in Woocommerce, using this add-on :https://github.com/XiaoFaye/WooCommerce.NET. My code is this:  

        var order = new Order() { status = "pending" };
        order.currency = "EUR";
        order.line_items.Add(new OrderLineItem()
        {
            id=44,
            product_id = 44,
            quantity=2
        }
          );
        order.customer_id = 1;
 
       Task ord = wc.Order.Add(order);
       ord.Wait();
But everytime it gives me this exception:
System.NullReferenceException: 'Object reference not set to an instance of an object.'

I have tried everything but no success...
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2018
Distinguished Expert 2018

Commented:
You haven't said which line gives you the error, so I'm going to guess that it's either line 3 (order.line_items.Add) or 12 (Task ord = wc.Order.Add(order);

Both of these lines look like they're adding an object to list, so it's possible that the list itself hasn't been initialised:

order.line_items = new List<OrderLineItem>();
order.line_items.Add(new OrderLineItem()
   ...

Open in new window

Author

Commented:
@Chris Stanyon
Hello and thanks for answering! Sorry that i didn't mention it... The line in question is this

order.line_items.Add(new OrderLineItem()
        {
            id=44,
            product_id = 44,
            quantity=2
        }
          );

Thanks again!
Chinmay PatelChief Technology Ninja
Distinguished Expert 2018

Commented:
On which line you get this exception? Is it when you try to add Products?
order.line_items.Add(new OrderLineItem()

Open in new window


Maybe you would want to first initialize line_items?

i.e.

order.line_items = new line_items()

Open in new window

Most Valuable Expert 2018
Distinguished Expert 2018
Commented:
Hey Pink Glitter,

Yeah ... that makes sense. Basically, you're trying to add a new OrderLineItem to the line_items property, and that property is null, so you'll need to follow my code example and init that property to a new list before adding items to it.

order.line_items = new List<OrderLineItem>();

Open in new window

Commented:
It depends on what your collection type is but, you could do something like this:
var order = new Order { status = "pending" };
order.currency = "EUR";
order.line_items = new List<OrderLineItem>() { new OrderLineItem { id = 44, product_id = 44, quantity = 2 } };
order.customer_id = 1;

Open in new window

-saige-

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial