LoginSignup
1
0

More than 3 years have passed since last update.

null許容型で躓いた

Posted at

背景

例の鬼教官の課題は続いている。
C#の課題プログラムの中でnull許容型について触れることがあったので
備忘録として残す。

課題

消費税(10%)商品と軽減税率対象商品の値段の出力プログラム

躓き

なんでmainの軽減税率計算はnull許容型(★1)でコンパイル通るのに
Book2クラスはnull許容型(★2)で書くと怒られるの~~~?(´;ω;`)

プログラム抜粋

class Program
{
    static void Main(string[] args)
    {
        //軽減税率商品の表示
        if(book0.軽減税率.HasValue)
        {
            double? x = book2.price * book2.軽減税率; //★1
            Console.WriteLine(x);
        }
        else
        {
            Console.WriteLine(book2.price);
        }
    }
}
class Book2
{
    public double 軽減税率get()
    {
        if(軽減税率.HasValue)
        {
            double x = _price * 軽減税率.Value; //★2 double? xにするとエラー
            return x ;
        }
        else
        {
            return _price * 消費税;
        }
    }
}

解答

★2はreturnを使っている。
つまり、doubleで返さないといけないからdoubleに指定しなければならない。
(基礎って大事ですね。。。)
ちなみにこの例だと、if文で値があれば、軽減税率を算出するようにしているので
★1は★2と同じ書き方にする。

まとめ

初心者なので基礎を定着させなきゃ~~

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0