0

By default datatype of 0 is int?

Error: Cannot implicitly convert type 'int' to 'short'.

public short CardType { get; set; }
CardType = 0;

Even this statment is fine.

short CardType = 0;

Note: Its not matter of casting. I want to understand why 0 cannot be short by default?

Thank you for giving useful understanding.

shaair
  • 945
  • 12
  • 24

4 Answers4

4

Yes, a numeric literal is, by default, an int unless you specify otherwise, for example a decimal can be declared using a M

var myDecimal = 0M;

F for float, L for long. But there isnt one for short you just need to rely on a cast:

public short CardType { get; set; }
CardType = (short)0;

On your edit:

Its not matter of casting. I want to understand why 0 cannot be short by default?

Its not relevant - Integers have to be some data type by default, in this case they just default to an int as per the Language specification

The type of an integer literal is determined as follows:

  • If the literal has no suffix, it has the first of these types in which its value can be represented: int, uint, long, ulong.
  • If the literal is suffixed by U or u, it has the first of these types in which its value can be represented: uint, ulong.
  • If the literal is suffixed by L or l, it has the first of these types in which its value can be represented: long, ulong.
  • If the literal is suffixed by UL, Ul, uL, ul, LU, Lu, lU, or lu, it is of type ulong.
Community
  • 1
  • 1
Jamiec
  • 133,658
  • 13
  • 134
  • 193
2

You need to do this:

public short CardType { get; set; }
CardType = (short)0;
Justin Harvey
  • 14,446
  • 2
  • 27
  • 30
1

Indeed, the type of 0 is an int in all the C-type languages; C# included.

There's no notation for a short literal.

So in those situations where the compiler cannot or is not allowed to disambiguate you need to use a cast:

CardType = (short)0;
Bathsheba
  • 231,907
  • 34
  • 361
  • 483
0

what you need is type casting

CardType = (short)0;

you may want to see this

Ali Faris
  • 17,754
  • 10
  • 45
  • 70