Reputation: 1502
I'm having trouble getting 'Year' to be a default value of the current Year if there is no value.
var now = DateTime.Now;
Year = int.Parse(bindingContext.ValueProvider.GetValue("Year").AttemptedValue ?? now.Year);
Upvotes: 2
Views: 4395
Reputation: 62564
It seems that
bindingContext.ValueProvider.GetValue("Year").AttemptedValue
is of string
type,??
operator expect both left/right values are of the same type.
As a case you can do now.Year.ToString():
var now = DateTime.Now;
Year = int.Parse(
bindingContext.ValueProvider.GetValue("Year").AttemptedValue
?? now.Year.ToString());
Upvotes: 2
Reputation: 15237
You have to apply the coalesce operator on two like types. String and int are not the same. Try this instead:
var year = 0;
if(!int.TryParse(bindingContext.ValueProvider.GetValue("Year").AttemptedValue, out year))
year = DateTime.Now.Year;
In the example, year will only be replaced if the AttemptedValue is parsable into an integer, otherwise it'll be the current year.
Upvotes: 7
Reputation: 103428
Use .ToString()
:
Year = int.Parse(bindingContext.ValueProvider.GetValue("Year").AttemptedValue ?? now.Year.ToString());
Both variables need to be of the same type.
Upvotes: 2
Reputation: 2989
The problem is that one of your values is a string and one is an int therefore it cannot decide what to convert too
You need to make sure that the types match and this problem should go away.
I would use .ToString() so that they are both strings.
Upvotes: 0