Home > Enterprise >  how to pass nullable field value as parameter to a function that takes none nullable parameters? [du
how to pass nullable field value as parameter to a function that takes none nullable parameters? [du

Time:09-22

I have got a field that is declared to accept nullable value. I am passing this field data to a method that takes no nullable parameters to preform some calculation and return the result. How Can I pass a a field value that its declared to take nullable variables to a method that expects none nullable variables.

Code

public static decimal CalculatePercentage(decimal price, decimal updatePrice, bool updateType)
{
    var precentage = (price / 100) * updatePrice;
    if (updateType)
        return  price  = precentage;
    else
        return price -= precentage;
}

// Passing the value of the model price ex 46.

   CalculatePercentage(model.price, updatePrice, updateType);

model

public decimal? Price { get; set; }

CodePudding user response:

Cast your value to the accepted one like this:

CalculatePercentage((decimal)model.price, updatePrice, updateType);

if it is null will throw error though

CodePudding user response:

you can use the .Value property of the nullable type

CalculatePercentage(model.Price?.Value, updatePrice, updateType);

assuming it has a value,

you can check its existence with the HasValue boolean property

  •  Tags:  
  • c#
  • Related