开发者

Working with Nullable types in C#

开发者 https://www.devze.com 2023-02-07 11:47 出处:网络
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 expl

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 InvoiceAmoun开发者_开发技巧t 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.
This code uses the null-coalescing operator, which evaluates to its first non-null operand.

Thus, 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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号