Cannot convert from 'long?' to 'long'

Problem

I use a code similar to the following to accept the value for a query string named Id on one of my pages of a .NET Razor Page application. It is an optional query string. Its value is then passed to another function for further processing. When I compile the code, I get the error message "cannot convert from 'long?' to 'long'". Here is my sample code with the error. 

 public class IndexModel : PageModel
    {
        private readonly ILogger<IndexModel> _logger;      
        public Decimal Result { get; set; }
        public IndexModel(ILogger<IndexModel> logger)
        {
            _logger = logger;
        }

        public void OnGet(long? Id)
        {
            if (Id != null)
            {
                Result = (Decimal)GetPower(Id, 2);
            }
        }
        private double GetPower(long Id, double p)
        {

            return Math.Pow(Id, p);
        }
    }

Solution

I got this error as Id is a nullable parameter. Its value will be null when the Id query string is not present in the URL. But the function GetPower accepts a variable of type long, which is not nullable. To fix this issue, I need to modify the function call as follows:

if (Id != null)
 {
    Result = (Decimal)GetPower(Id.GetValueOrDefault(), 2);
 }           

The GetValueOrDefault Method retrieves the value of the current Nullable<T> object, or the default value of the underlying type. If an integer data type is used instead of long, the error message will be this "cannot convert from 'int?' to 'int'". The solution for that also is the same. So the final code will be the following:

 public class IndexModel : PageModel
    {
        private readonly ILogger<IndexModel> _logger;
        public Decimal Result { get; set; }
        public IndexModel(ILogger<IndexModel> logger)
        {
            _logger = logger;
        }
        public void OnGet(long? Id)
        {
            if (Id != null)
            {
                Result = (Decimal)GetPower(Id.GetValueOrDefault(), 2);
            }
        }
        private double GetPower(long Id, double p)
        {

            return Math.Pow(Id, p);
        }
    }

 


Search