CoderRoller
CoderRoller

Reputation: 1259

Decimal value can not be recognized/parsed in my constructor

I am following an example and it has a class that goes like this:

public class Price
{

private decimal _sellingPrice;
private decimal _rrp;

public Price(decimal RRP, decimal SellingPrice)
{
            _rrp = RRP;
            _sellingPrice = SellingPrice;
}

}

This class is then constructed with values queried from a table using LINQ:

var products = from p in new ShopDataContext().Products                           
                           select new Model.Product
                           {
                               Id = p.ProductId,
                               Name = p.ProductName,
                               Price = new Price(p.RRP, p.SellingPrice)
                           };

On the example this seems to work, however I am getting this error:

Price = new Price(p.RRP, p.SellingPrice)
The best overload method match has some invalid arguments
Argument 1: cannot convert from 'decimal?' to 'decimal' 

The p.RRP and p.SellingPrice values are taken from a table as System.Decimal types and apparently nullable by default hence the exception, tho in the example this seems to run ok, so Why is that?. Is there anything I am missing?. I am experimenting with C# and I know its a strict language by default so there is no option to turn off and make this work in my understanding.

Thank you for your insight.

Upvotes: 1

Views: 344

Answers (2)

Andrei
Andrei

Reputation: 56716

In C# decimal? cannot be converted implicitly to decimal. So the only way for you to work it out is to make the explicit convert. For example:

var products = from p in new ShopDataContext().Products                           
               select new Model.Product
               {
                   Id = p.ProductId,
                   Name = p.ProductName,
                   Price = new Price(
                        p.RRP ?? 0,
                        p.SellingPrice ?? 0)
               };

Upvotes: 1

Peter Gluck
Peter Gluck

Reputation: 8236

The problem is your query is returning a nullable decimal type rather than a decimal type. You need to modify your constructor like this:

public Price(decimal? RRP, decimal? SellingPrice) {
        _rrp = (decimal) RRP;
        _sellingPrice = (decimal) SellingPrice;
}

If you want to be thorough in checking for possible errors, you can use one of the techniques described in this article.

Upvotes: 1

Related Questions