Dec
25
2012

Type of conditional expression cannot be determined as ‘byte’ and ‘int’

In this article we are going to see how to solve error that says – conditional expression cannot be determined as.

I was working on small chunk of C#.net code on VS 2005 and ended up with an error at compile time that says –

Type of conditional expression cannot be determined as ‘byte’ and ‘int’ convert implicitly to each other

[Please note] – In VS 2010, you might get below error –

Cannot implicitly convert type ‘int’ to ‘byte’. An explicit conversion exists (are you missing a cast?)

Cannot implicitly convert type 'int' to 'byte'
Error – Cannot implicitly convert type ‘int’ to ‘byte’

Look at below code snippet that was generating error –

int firstIntegerValue = 999;
byte byteValue = 0;
int integerInput = 0;
Console.WriteLine(“Enter any digit : “);
int.TryParse(Console.ReadLine(), out integerInput);
byteValue = (integerInput.Equals(0) ? Convert.ToByte(firstIntegerValue) : 1);

Now, where is the issue in above code?. Look at the highlighted part. This is the cause of the error.

Now the question here is how to solve error – “Type of conditional expression cannot be determined as ‘byte’ and ‘int’. Convert implicitly to each other”. The good thing is i resolved the error in minutes. To resolve the issue, I just used the type conversion in highlighted part. See below affected code line –

byteValue = (integerInput.Equals(0) ? Convert.ToByte(firstIntegerValue) : (byte)1);

It worked like a charm and above compilation error disappeared.

Why “Type of conditional expression cannot be determined as ‘byte’ and ‘int’ convert implicitly to each other”

If you look at the second line of first snippet i.e. “byte byteValue = 0;” – a value “0” is directly assigned to byte type. Then why it is not working in highlighted part of first code snippet?

The answer is – Here we used ternary expression and one of the rules of ternary operation says – “either the type of first expression & second expression must be same, or an implicit conversion must exist from one type to other.

So guys, if you are facing same issue for any type conversion in ternary expression then do not forget to make type same of both expressions or make an explicit type conversion in both expressions.

If you find this article helpful, then could you please share the article on your social network?

More articles –

About the Author: Ashish Ramteke

Ashish Ramteke is a Software Professional, Part time blogger and founder of C# Tutorials, a popular blog on C#.Net. Ashish is having 6 years of work experience and an engineering degree in Computer Science and Engg.

Leave a comment