473,395 Members | 1,797 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

Why is the conditional operator so weird?

Consider this code (.Net 2.0) which uses a nullable type:

private void button1_Click(object sender, System.EventArgs e)
{
DateTime? nullableDate;
nullableDate = (condition) ? null : DateTime.Now;
}

When the condition is false, I want to return null. If true, I want to
return the current date/time.

The compiler error I get is:

Type of conditional expression cannot be determined because there is no
implicit conversion between '<null>' and 'System.DateTime'

Why should it matter if the true and false expressions can be converted
to *each other*? As long as each of the expressions can be assigned to
the result, it should be allowed! Since both null and DateTime.Now can
be assigned to the variable 'nullableDate', I don't understand why the
line is not allowed?

If you refactor this code to this:

if (true != false)
nullableDate = null;
else
nullableDate = DateTime.Now;

It works fine. Why do the true/false parts of the ternary operator
have to have implicit conversions between them? As long as each of
them are assignable to the result variable, it seems to me that it
should work?

Why was it designed this way?

Nov 17 '05 #1
6 12116
All you have to do is Explicitly declare the type of null as shown below:

DateTime? nullableDate = null;
nullableDate = ( true ) ? (DateTime?)null : DateTime.Now;
Gregory McCallum, MCSD
gm*******@honovi.com
"Chris Dunaway" wrote:
Consider this code (.Net 2.0) which uses a nullable type:

private void button1_Click(object sender, System.EventArgs e)
{
DateTime? nullableDate;
nullableDate = (condition) ? null : DateTime.Now;
}

When the condition is false, I want to return null. If true, I want to
return the current date/time.

The compiler error I get is:

Type of conditional expression cannot be determined because there is no
implicit conversion between '<null>' and 'System.DateTime'

Why should it matter if the true and false expressions can be converted
to *each other*? As long as each of the expressions can be assigned to
the result, it should be allowed! Since both null and DateTime.Now can
be assigned to the variable 'nullableDate', I don't understand why the
line is not allowed?

If you refactor this code to this:

if (true != false)
nullableDate = null;
else
nullableDate = DateTime.Now;

It works fine. Why do the true/false parts of the ternary operator
have to have implicit conversions between them? As long as each of
them are assignable to the result variable, it seems to me that it
should work?

Why was it designed this way?

Nov 17 '05 #2
Chris,

This is from the C# language specification:

The second and third operands of the ?: operator control the type of the
conditional expression. Let X and Y be the types of the second and third
operands. Then,

- If X and Y are the same type, then this is the type of the conditional
expression.
- Otherwise, if an implicit conversion (§6.1) exists from X to Y, but
not from Y to X, then Y is the type of the conditional expression.
- Otherwise, if an implicit conversion (§6.1) exists from Y to X, but
not from X to Y, then X is the type of the conditional expression.
- Otherwise, no expression type can be determined, and a compile-time
error occurs.

Here are why the conditions don't apply to your example.

- X is null, so there is no type associated with it. You don't have a
cast either saying what this should be a null of.
- There is no conversion from X (null) to Y (DateTime) that is implicit,
so this condition doesn't apply.
- There is no conversion from Y (DateTime) to X (null) which is
implicit, so this condition doesn't apply.
- This condition applies, because no expression type can be determined.

Now, you can get around this one of three ways. The first is to cast
both sides to DateTime?, which would result in condition one being
satisfied. If you cast the null to DateTime?, then condition three is
satisfied, since there is an implicit conversion from DateTime to DateTime?.
If you cast the DateTime to DateTime?, then condition two is satisfied,
since there is an implicit conversion from null to DateTime?.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"Chris Dunaway" <du******@gmail.com> wrote in message
news:11**********************@g49g2000cwa.googlegr oups.com...
Consider this code (.Net 2.0) which uses a nullable type:

private void button1_Click(object sender, System.EventArgs e)
{
DateTime? nullableDate;
nullableDate = (condition) ? null : DateTime.Now;
}

When the condition is false, I want to return null. If true, I want to
return the current date/time.

The compiler error I get is:

Type of conditional expression cannot be determined because there is no
implicit conversion between '<null>' and 'System.DateTime'

Why should it matter if the true and false expressions can be converted
to *each other*? As long as each of the expressions can be assigned to
the result, it should be allowed! Since both null and DateTime.Now can
be assigned to the variable 'nullableDate', I don't understand why the
line is not allowed?

If you refactor this code to this:

if (true != false)
nullableDate = null;
else
nullableDate = DateTime.Now;

It works fine. Why do the true/false parts of the ternary operator
have to have implicit conversions between them? As long as each of
them are assignable to the result variable, it seems to me that it
should work?

Why was it designed this way?

Nov 17 '05 #3
what if you are not assigning the result of the ternary operator? how can
you figure out the type of the expression without the rule in place?

Console.WriteLine( (condition) ? null : DateTime.Now );

which WriteLine overload is callable here? and consider nested ternary
operator

(condition1) ? DateTime.MinValue : (condition2) ? null : DateTime.Now;

now you are really in trouble. how can you easily determine this is type
safe?

"Chris Dunaway" wrote:
Consider this code (.Net 2.0) which uses a nullable type:

private void button1_Click(object sender, System.EventArgs e)
{
DateTime? nullableDate;
nullableDate = (condition) ? null : DateTime.Now;
}

When the condition is false, I want to return null. If true, I want to
return the current date/time.

The compiler error I get is:

Type of conditional expression cannot be determined because there is no
implicit conversion between '<null>' and 'System.DateTime'

Why should it matter if the true and false expressions can be converted
to *each other*? As long as each of the expressions can be assigned to
the result, it should be allowed! Since both null and DateTime.Now can
be assigned to the variable 'nullableDate', I don't understand why the
line is not allowed?

If you refactor this code to this:

if (true != false)
nullableDate = null;
else
nullableDate = DateTime.Now;

It works fine. Why do the true/false parts of the ternary operator
have to have implicit conversions between them? As long as each of
them are assignable to the result variable, it seems to me that it
should work?

Why was it designed this way?

Nov 17 '05 #4
In C# (and in Java, and in C++, and in...) right-hand-side expression
typing is never determined by the target left-hand-side variable type.
The type of the expression stands on its own and must be determined on
its own. The compiler never looks at where the value is going; it looks
only at the consituent parts of the expression to determine the
expression type, regardless of the operators involved.

It would be nice if the compiler were smart enough to ask the question,
"Is there a third type to which both of these types could be converted
that could serve as the type for the overall expression?" However, that
may be too much to ask. :-)

Nov 17 '05 #5
Thanks for the response. It did help. But my question was WHY the two
operands on either side of the : had to have implicit conversions
available. That question was answered by the other posters.

Nov 17 '05 #6
Thanks Bruce and Daniel, now I understand why it behaves the way it
does.

Nov 17 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: TheKeith | last post by:
I just wrote the following script for something I'm working on: ---------------------------------------------------------------------------- ------------------- <html> <head> <script...
3
by: Jouke Langhout | last post by:
Hello all! For quite some time now, I've got the following problem: Access won't close properly when a user closes the application. An ACCESS process stays active and that process can only be...
6
by: Mahesh Tomar | last post by:
Please see the code below :- void func() { unsigned char x,y,z=1; (z==1) ? (x) : (y) = 1; /* Compiles OK */ ((z==1) ? (x) : (y)) = 1; /* Compiler generates an error "Variable expected" */ }
4
by: mux | last post by:
Hi I found out that the following piece of code throws an error. 1 #include "stdio.h" 2 3 int main() 4 { 5 int a,b; 6 a= 10;
9
by: Marty | last post by:
Hi, Does using the the conditional operator (?:) instead of the common "if" statement will give a performance gain in a C# .NET 2003 application (even in C# .NET 2005?). What is the advantage...
5
by: paulo | last post by:
Can anyone please tell me how the C language interprets the following code: #include <stdio.h> int main(void) { int a = 1; int b = 10; int x = 3;
15
by: Nicholas M. Makin | last post by:
I was just thinking that I understood the conditional operator when I coded the following expecting it to fail: int a= 10, b= 20, c= 0; ((a < b) ? a : b) = c; // a=0 a=20; b= 10; ((a < b) ? a...
3
by: somenath | last post by:
Hi All, I have one question regarding the conditional operator. In the draft C99 standard it is mentioned that "1 The following are the sequence points described in 5.1.2.3: -- The call to a...
13
by: Neal Becker | last post by:
In hindsight, I am disappointed with the choice of conditional syntax. I know it's too late to change. The problem is y = some thing or other if x else something_else When scanning this my...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.