Avatar of pink glitter
pink glitter
 asked on

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

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...
* AddinsC#Microsoft Visual Studio

Avatar of undefined
Last Comment
it_saige

8/22/2022 - Mon
Chris Stanyon

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

pink glitter

ASKER
@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 Patel

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

Your help has saved me hundreds of hours of internet surfing.
fblack61
ASKER CERTIFIED SOLUTION
Chris Stanyon

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
it_saige

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-