Home > front end >  How to conditionally init an object in c#?
How to conditionally init an object in c#?

Time:03-02

I have an old function that sends off daily Sales Receipts to Quickbooks Online and wanted to also have it send off any Refund Receipts for any refunds that may have occurred.

The old main sale object is used throughout the function, having it's properties set as required. I would like to use this same bit of code for both Sales Receipts and Refund Receipts but Sales Receipts need sale set to a SalesReceipt Intuit object and Refund Receipts need the sale set to the Intuit RefundReceipt object.

I tried this:

if (inData.Product[d, l].Contains("Refund"))
{
    RefundReceipt sale = new RefundReceipt();
} else {
    SalesReceipt sale = new SalesReceipt();
} 

But sale's scope is limited to the confines of the if/else block.

I could just duplicate the function but that seems messy for just a simple assignment of an object.

Can I do this somehow?

TIA. :-)

CodePudding user response:

why you don' t use just object type

object sale;
if (inData.Product[d, l].Contains("Refund"))
{
     sale = new RefundReceipt();
} else {
     sale = new SalesReceipt();
} 

use

func(sale as RefundReceipt);

or call function directly from code

if (inData.Product[d, l].Contains("Refund"))
{
     func(new RefundReceipt());
} else {
     func (new SalesReceipt());
} 

CodePudding user response:

Extending Serge answer you can do this

if (inData.Product[d, l].Contains("Refund"))
{
    func(new RefundReceipt());
} else {
    func(new SalesReceipt());
} 

and func has

 void func(Object receipt){
    if(receipt is RefundRecipt)
    {
        var refund = receipts as RefundRecipt;
        ......
     }
     else
     {
        var refund = receipts as SalesRecipt;
        ....
     }
  }

however far better would be to have a clas heirarchy

 public abstract class Receipt{
 }

 public class SalesReceipt : Receipt{
 }

 public class RefundReceipt : Receipt{
 }
               

CodePudding user response:

objects can be initialized with null

    if (inData.Product[d, l].Contains("Refund"))
{
    RefundReceipt sale = null;
 } else {
    SalesReceipt sale = null;
} 

or if it is defined before the if and it has some value you can clear as follow

 sale.clear();
  •  Tags:  
  • c#
  • Related