Mega Code Archive

 
Categories / C# Book / 01 Language Basics
 

0064 Integral type promotion

byte, sbyte, short and ushort is promoted to int during the calculation. using System; class Program { static void Main(string[] args) { byte i = 5; byte j = 6; byte result = i + j; } } The code above generates the following compiling error: C:\g>csc Program.cs Microsoft (R) Visual C# 2010 Compiler version 4.0.30319.1 Copyright (C) Microsoft Corporation. All rights reserved. Program.cs(10,23): error CS0266: Cannot implicitly convert type 'int' to 'byte'. An explicit conversion exists (are you missing a cast?) Since the i and j are promoted to int and the result of i + j is int,which cannot be converted to byte. To fix it, add a cast: using System; class Program { static void Main(string[] args) { byte i = 5; byte j = 6; byte result =(byte) (i + j); Console.WriteLine(result); } } The output: 11