1

I am trying to assign 0 to a short variable from a condition and it throws compile time error that

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

Refer below screenshot. The salesLineInput.Discount is a short and SalesLineEntity.Discount is a Nullable<double>:

enter image description here

This is some other code I tried (not the same as in the screenshot):

    if(SalesLineEntity.Discount.HasValue)
       salesLineInput.Discount = (short)(SalesLineEntity.Discount * 100);
    else
       salesLineInput.Discount = 0;

Why does the if work, but the ternary doesn't?

mjwills
  • 23,389
  • 6
  • 40
  • 63
Kishan Vaishnav
  • 2,273
  • 1
  • 17
  • 45
  • 1
    Please always post code as text instead of images, so it is searchable and can be copied to reproduce the problem or quote it in answers. And since `0` is taken by the compiler as `int`, the result type of the `?` operator is `int`. You either need to cast the `0` or the whole statement to `short` – René Vogt May 09 '19 at 06:59
  • 1
    You get this compilation error because there is a mismatch between the types of both return values in the conditional statement. On one side you return a short (explicit cast), on the other hand an int. Note that you [cannot specify without casting](https://stackoverflow.com/a/8670736/1507014) that 0 is indeed a short in your case. So [the answer by TheGeneral](https://stackoverflow.com/a/56053780/1507014) is the right way to do it. – Bentoy13 May 09 '19 at 07:02
  • The simplest fix is to change your code to `salesLineInput.Discount = (short)((SalesLineEntity.Discount ?? 0) * 100);` – mjwills May 09 '19 at 07:05
  • @mjwills Now I get it I was searching for a numeric literal suffix for the short type which isn't available. So I have to explicitly cast it. This is my answer. – Kishan Vaishnav May 09 '19 at 07:18

1 Answers1

0

Cast the whole statement to short

 salesLineItem.Discount = (short)(condition ? somecalc : 0);

or

 salesLineItem.Discount = condition ? somecalc : (short)0;
TheGeneral
  • 79,002
  • 9
  • 103
  • 141