473,748 Members | 2,793 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Why is the conditional operator so weird?

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

private void button1_Click(o bject sender, System.EventArg s 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.DateTim e'

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 12140
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*******@honov i.com
"Chris Dunaway" wrote:
Consider this code (.Net 2.0) which uses a nullable type:

private void button1_Click(o bject sender, System.EventArg s 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.DateTim e'

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.co m

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

private void button1_Click(o bject sender, System.EventArg s 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.DateTim e'

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.WriteLi ne( (condition) ? null : DateTime.Now );

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

(condition1) ? DateTime.MinVal ue : (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(o bject sender, System.EventArg s 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.DateTim e'

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
4458
by: TheKeith | last post by:
I just wrote the following script for something I'm working on: ---------------------------------------------------------------------------- ------------------- <html> <head> <script type="text/javascript"> function KP_growit(subject,widthto,heightto) { var target = document.getElementById(subject);
3
5933
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 terminated by pressing ++ and then terminate the process. I searched the entire internet and found out that there could be two things wrong (both of them are mentioned in the bug list on the access
6
3664
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
4688
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
4782
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 of using it in C# other than typing shorter if ? Thanks, Marty
5
2903
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
1802
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 : b) = c; //b=0 Now since the expresion 5 = c is not valid I did not expect the above to work. But it does work. Why? I thought that the ?: operator would evaluate
3
2473
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 function, after the arguments have been evaluated (6.5.2.2). -- The end of the first operand of the following operators: logical AND && (6.5.13);
13
1550
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 eye tends to see the first phrase and only later notice that it's conditioned on x (or maybe not notice at all!). Particularly if 'some thing or other' is long or complicated.
0
8991
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8830
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9370
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8242
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6796
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6074
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4602
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4874
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2782
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.