C # Ternary operator returning different types

I am trying to use ternar to return different types, although I seem to run into some problems. My question is: can a triple operator not return different types?

// This line causes an error propertyGrid.Instance = (directoryRecord.directoryInfo != null) ? directoryRecord.directoryInfo : directoryRecord.fileInfo; // Compiles fine propertyGrid.Instance = directoryRecord.directoryInfo; // Compiles fine propertyGrid.Instance = directoryRecord.fileInfo; 

Error

The conditional expression type cannot be determined because there is no implicit conversion between 'System.IO.DirectoryInfo' and 'System.IO.FileInfo'

+4
source share
2 answers

No, it is not. A conditional statement expression has a specific type. Both types used in the expression must be of the same type or implicitly convertible to each other.

You can make it work as follows:

 propertyGrid.Instance = (directoryRecord.directoryInfo != null) ? (object)directoryRecord.directoryInfo : (object)directoryRecord.fileInfo; 
+10
source

No.
Both return values ​​must ultimately be stored in the same variable that will contain the result.
Therefore, the compiler should have a way to determine the type of this variable / storage area.
Because of the type safety of the language, you need to know the type, and they will both get the same variable.

+2
source

Source: https://habr.com/ru/post/1439801/


All Articles