Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Tertiary assignment on a nullable type wont compile if one case is non nullable and one is nullable #2944

Closed
KieranDevvs opened this issue Nov 8, 2019 · 5 comments

Comments

@KieranDevvs
Copy link

I'm trying to assign a value to a null-able type via a tertiary assignment where:
case true: assign non-nullable
case false: assign null

DateTime? assignee;
DateTime assignment;
var condition = false;

assignee = condition ? assignment: null;

This results in the compile error: Cannot convert DateTime to nullable.

I would assume that the compiler would translate this into something like:

DateTime? assignee;
DateTime assignment;
var condition = false;

if(condition) {
    assignee = assignment;
}else{
    assignee = null;
}

Which compiles fine.
Whats actually going on here?

@spydacarnage
Copy link

You can use:

assignee = condition ? assignment : default(DateTime?)

@ronnygunawan
Copy link

ronnygunawan commented Nov 8, 2019

Related to #2823 #33

@KieranDevvs
Copy link
Author

You can use:

assignee = condition ? assignment : default(DateTime?)

Seems like a bit of a hack, but I guess it works for now.

@333fred
Copy link
Member

333fred commented Nov 8, 2019

This would be addressed by #2823, which is currently on the table for c# 9

@gafter
Copy link
Member

gafter commented Nov 16, 2019

Closing as duplicate

@gafter gafter closed this as completed Nov 16, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants