Implementing a TryXXX method: Returning a nullable vs using out keyword

I'm writing some methods at the moment that are of a "TryThisElseNull" type pattern like TryParse for example.

Originally my methods would return bool and this would let the caller know if the method was successful. If it was then it could safely use the value being used via the out keyword.

But then I was looking at StackOverflow and one users suggestion was to in fact not use the out keyword pattern and instead return a nullable.

The argument for this was that the TryParse set of methods were written before nullable types were added and that by returning a nullable the calling code would be easier to understand and would also not need a variable declaring to use with the out parameter.

What is /r/csharp's opinion on this? Which way do you prefer to use? Personally I'm leaning more towards the nullable type, because I've only been learning C# when I've had chance for a couple of years and up until now I've never needed to use the out keyword for my own methods whereas I've use nullable before.

by SuperImaginativeName via /r/csharp

Leave a Reply