简体   繁体   中英

Working with Nullable types in C#

I have Nullable properties defined in my class which take part in calculations and xml writing. As you all know, when any null value takes part in a calculation, the result is always null. I will explain it by examle ::

Code for properties and calculation :

public decimal? Amount { get; set; }
public decimal? VatAmount { get; set; }
public decimal? InvoiceAmount { get; set; }
.
.
public decimal Add()
{
     //HERE I NEED 0 TO PERFORM THE CALCULATION
     this.InvoiceAmount = this.Amount + this.VatAmount;
     return this.InvoiceAmount
}
.
.
public string Insert()
{
     XDocument doc1 = XDocument.Load(@"Transactions.xml");
        var record = from r in doc1.Descendants("Transaction")
                     where (int)r.Element("Serial") == Serial
                     select r;
        foreach (XElement r in record)
        {
             //HERE I WANT NULL VALUES RETAINED  
             r.Element("DebitNote").Add(new XElement("InvoiceAmount", this.InvoiceAmount), new XElement("VatAmount", this.VatAmount), new XElement("Amount", this.Amount));
        }
        doc2.Save(@"Transactions.xml");
        return "Invoice Created Successfully";

As you can see until the value of Amount or VatAmount is null, the InvoiceAmount will always be null. How can i work around this ??. One possible solution is to set the default value of private variable of Amount and VatAmount equal to 0 . But with this setting when i add record to xml, the value for Amount and InvoiceAmount will be entered 0; whereas i want to retain null if nothing is entered in this case.

Let me know how can both conditions be satisfied. Don't necessarily need to write code, can tell me in General

Thanks in advance !!

You can write Amount ?? 0 Amount ?? 0 .
This code uses the null-coalescing operator , which evaluates to its first non-null operand.

Thus, Amount ?? 0 Amount ?? 0 will evaluate to Amount if it's non-null and 0 if it is null.

How about using the GetValueOrDefault method of Nullable<T> in the calculation? This way you will get zeroes for your calculation but retain the nulls for your xml.

this.InvoiceAmount = this.Amount.GetValueOrDefault() 
                   + this.VatAmount.GetValueOrDefault(); 
if (this.Amount.HasValue) 
    this.InvoiceAmount += this.Amount;
if (this.VatAmount.HasValue) 
    this.InvoiceAmount += this.VatAmount;

I think you will have to check for null in you add method and treat it as zero.

eg:

//HERE I NEED 0 TO PERFORM THE CALCULATION
 this.InvoiceAmount = this.Amount ?? decimal.Zero + this.VatAmount ?? decimal.Zero;
 return this.InvoiceAmount

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