简体   繁体   中英

How to conditionally init an object in c#?

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. :-)

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

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{
 }
               

I'm sorry for my absence. I've had my head in other stuff. I finally just said let's quit being cute and just make two functions one for SalesReceipts and one for RefundReceipts. Easier to debug, easier to maintain.

Thanks for all your help and suggestions, maybe it will help me or someone again sometime.

:Ron

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 as List before the if and it has some value you can clear as follow

 sale.clear();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM