-
Notifications
You must be signed in to change notification settings - Fork 4.8k
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
Proposal: Nullable.TryGetValue #18260
Comments
@jamesqo, Why not do the following: int? nullable = Foo();
if (nullable.HasValue)
{
DoSomething(nullable.GetValueOrDefault());
}
else
{
DoSomethingElse();
} Calling Also you can implement an extension method that does what you want (although you have to write a separate extension for each public static class NullableExtensions
{
public static bool TryGetValue(this int? nullable, out int value)
{
value = nullable.GetValueOrDefault();
return nullable.HasValue;
}
} Note: I do like the cleanliness/readability of your proposal. |
@tannergooding public static bool TryGetValue<T>(this T? nullable, out T value) where T : struct
{
value = nullable.GetValueOrDefault();
return nullable.HasValue;
}
} |
Not sure how useful this would be, since in C# 7.0, you should be able to use pattern matching for this: if (Foo() is int value)
{
DoSomething(value);
}
else
{
DoSomethingElse();
} |
@svick, I think that really depends on the code generated for your sample. I believe the |
@tannergooding Given that @svick's code sample essentially makes this whole thing redundant in C# 7, I guess it's best to close this. |
A common pattern when working with nullables is to do something with the value if the nullable has one, or do something else if it doesn't. This is most commonly written like this:
The problem here is that even though we know that the nullable must have a value within the
HasValue
block, the compiler can't formally assume that and we have to explicitly unwrap it usingValue
. It would be nice if we provided aTryGetValue
method on Nullable to aggregate these 2 operations (checking if the value exists, then unwrapping it) into one:As you can see it's possible to write more concise code with
TryGetValue
since we only need the nullable once, and it doesn't need to get saved in a local variable.This will work even better when C# 7 introduces out var, since we can skip the explicit
int value;
declaration and instead writeout int value
.Proposed API
The text was updated successfully, but these errors were encountered: