Search code examples
c#.netasp.net-mvcasp.net-mvc-3nullable

Casting error in MVC


I am developing a MVC app. with razor syntax. I am trying to delete one value from another.

  @{
   double DeductedAmount1 = @Model.SanctionedAmount - @Model.DeductionAmount;         
  }

This showing error as

Cannot implicitly convert type 'double?' to 'double'. An explicit conversion exists (are you missing a cast?)

Issue Solved , thanks To Darren Davies

dAmount1 = (double)@Model.SanctionedAmount.Value - (double)@Model.DeductionAmount;

Solution

  • Use double?

    double? DeductedAmount1 = @Model.SanctionedAmount - @Model.DeductionAmount; 
    

    Looks like SanctionedAmount or DeductionAmount are type of nullable double

    You can also use .Value on the Nullable double. For instance if SanctionedAmount is of type double? and DeductionAmount is of type double you can do:

     double DeductedAmount1 = @Model.SanctionedAmount.Value - @Model.DeductionAmount;
    

    Also you can use a cast

     double DeductedAmount1 = (double)@Model.SanctionedAmount.Value - (double)@Model.DeductionAmount;