5 ms·
C# offers this via Nullable<T>: Nullable<int> someNumber = foo.TryAndGetSomeNumber(); if(someNumber && someNumber.HasValue) doSomething( someNumber.Val
by troygoode 15y ago
C# offers this via Nullable<T>:
Nullable<int> someNumber = foo.TryAndGetSomeNumber();
if(someNumber && someNumber.HasValue)
doSomething( someNumber.Value );
- arethuza 15y agoWhy don't you use int? rather than Nullable<int> - aren't they equivalent?
- lallysingh 15y agoThe point is, all values of the int are available. Null is stored somewhere outside the underlying int.
- arethuza 15y agoIt was just a question about the syntax used - why type Nullable<int> when there is direct syntactical support in C# for nullable types - in this case you could simply type int? rather than Nullable<int>
- endianswap 15y agoAt the very least Nullable<T> is a lot friendlier to search than T? if you want to learn more on the subject.
- bfung 15y agonot everyone is familiar with C#, and Nullable<int> conveys better meaning in writing to that kind of audience.
- deleted 15y ago[deleted]
- troygoode 15y agoint? is syntactic sugar for Nullable<int>, which didn't seem worth getting into :-)
- dkersten 15y agoif(someNumber && someNumber.HasValue) You still have to remember to do this check. Will the compiler complain if you use someNumber.Value without checking that its valid first? If not, then its not really the same thing. The point of Haskell's Maybe is that the compiler will make sure that you take both cases (that there is a value and that there isn't a value) into account (because to extract the value you must pattern match and pattern matches must be exhaustive, otherwise you get a compile error).
- chc 15y agoEh, that's putting it a little too strongly. Haskell is a nice language, but it still doesn't protect you from all your mistakes. The easiest way to extract the value in Haskell is fromJust, which simply errors if no value was returned. I do agree that Haskell makes it more natural, though.
- troygoode 15y agoThe compiler won't, no - but many/most developers use static analysis tools like ReSharper which WILL tell you that you have a possible NullReferenceException there if you don't check it.
- bmm6o 15y agoMore idiomatic C# might be: int result; if (foo.TryAndGetSomeNumber(out result)) doSomething(result); There might also be a foo.GetSomeNumber() that returns an int or throws on failure. [fixed formatting]
- troygoode 15y agoI disagree that your example is more idiomatic. Maybe pre-3.0...