I'm reading up on core C# programming constructs and having a hard time wrapping my head around the out parameter modifier. I know what it does by reading but am trying to think of a scenerio when I would use it.
Can someone give me a real-world example? Thanks.
The main motivation to using an out parameter is to allow a function to return multiple values to the caller and everyone else provided examples in the framework. I'll take a different approach to answering your question by exploring the reasoning behind having out parameters in the first place. I won't write out actual examples but describe them.
Normally you have only one mechanism to return values, the function's return value. Sure you could use a global (static) or instance variables too but that's not very practical nor safe to do in general (for reasons I won't explain here). Prior to .NET 3.5, there wasn't a really practical way to return multiple values from a function. If out or ref modifiers were not available, you would have a few options:
If all your values had the same type, you could return some collection of the values. This is perfectly fine in most cases, you could return an array of number, list of strings, whatever. This is perfect if all the values were related in exactly the same way. i.e., All numbers were the number of items in a container, or the list was of names of guests at a party. But what if the values you returned represented different quantities? What if they had different types? A list of objects could hold them all but it is not a very intuitive way to manipulate that sort of data.
For the case when you need to return multiple values of different types, the only practical option you had was to create a new class/struct type to encapsulate all these values and return an instance of that type. Doing so you could return strongly typed values with intuitive names and you could return multiple values this way. The problem is that in order to get that, you had to define the type with a specific name and everything just to be able to return multiple values. What if you wanted to return only two values which were simple enough making it impractical to create a type for it? You have a couple more options again:
You could create a set of generic types to contain a fixed amount of values of varying types (like a tuple in functional languages). But it is not as appealing to do so in a reusable manner since it wasn't part of the framework at the time. It could be put in a library but now you add a dependency on that library just for the sake of these simple types. (just be glad that .NET 4.0 now includes the Tuple type) But this still doesn't solve the fact that these are simple values which means added complexity for a simple task.
The option that was used was to include an out modifier which allows the caller to pass a "reference" to a variable so that the function may set the referenced variable as another way to return a value. This way of returning values was also available in C and C++ in many ways for the same reasons and played a role in influencing this decision. However the difference in C# is that for an out parameter, the function must set the value to something. If it doesn't, it results in a compiler error. This makes this less error prone since by having an out parameter, you're promising the caller that you will set the value to something and they can use it, the compiler makes sure you stick to that promise.
A note on the typical usage of the out (or ref) modifier, it will be rare to see more than one or two out parameters. In those cases, it will almost always be a much better idea to create the encapsulating type. You would typically use it if you needed just one more value to return.
However since C#-3.0/.NET-3.5 with the introduction of anonymous types and tuples introduced in .NET 4.0, these options provided alternative methods to return multiple values of varying types easier (and more intuitive) to do.
there are many scenarios where you would use it, but the main one would be where your method needs to return more then one parameter. Take, for example, the TryParse methods on int type. In this case, instead of throwing an exception a bool is returned as a success/failure flag and the parsed int is return as the out param. if you were to call int.Parse(...) you could potentially throw an exception.
string str = "123456";
int val;
if ( !int.TryParse(str,out val) )
{
// do some error handling, notify user, etc.
}
Sure, take a look at any of the TryParse methods, such as int.TryParse:
The idea is you actually want two pieces of information: whether a parse operation was successful (the return value), and, if so, what the result of it actually was (the out parameter).
Usage:
string input = Console.ReadLine();
int value;
// First we check the return value, which is a bool
// indicating success or failure.
if (int.TryParse(input, out value))
{
// On success, we also use the value that was parsed.
Console.WriteLine(
"You entered the number {0}, which is {1}.",
value,
value % 2 == 0 ? "even" : "odd"
);
}
else
{
// Generally, on failure, the value of an out parameter
// will simply be the default value for the parameter's
// type (e.g., default(int) == 0). In this scenario you
// aren't expected to use it.
Console.WriteLine(
"You entered '{0}', which is not a valid integer.",
input
);
}
Many developers complain of out parameters as a "code smell"; but they can be by far the most appropriate choice in many scenarios. One very important modern example would be multithreaded code; often an out parameter is necessary to permit "atomic" operations where a return value would not suffice.
Consider for example Monitor.TryEnter(object, ref bool), which acquires a lock and sets a bool atomically, something that wouldn't be possible via a return value alone since the lock acquisition would necessarily happen before the return value were assigned to a bool variable. (Yes, technically ref and out are not the same; but they're very close).
Another good example would be some of the methods available to the collection classes in the System.Collections.Concurrent namespace new to .NET 4.0; these provide similarly thread-safe operations such as ConcurrentQueue<T>.TryDequeue(out T) and ConcurrentDictionary<TKey, TValue>.TryRemove(TKey, out TValue).
Output parameters are found all over the .NET framework. Some of the uses I see most often are the TryParse methods, which return a boolean (indicating whether or not the parse was valid) and the actual result is returned via the output parameter. While it's also very common place to use a class when you need to return multiple values, in such an example as this it's a little heavy handed. For more on output parameters, see Jon Skeet's article on Parameter passing in C#.
Simple, when you have a method that returns more than one value.
One of the most "famous" cases is Dictionary.TryGetValue:
string value = "";
if (openWith.TryGetValue("tif", out value))
{
Console.WriteLine("For key = \"tif\", value = {0}.", value);
}
else
{
Console.WriteLine("Key = \"tif\" is not found.");
}
As others have said - out parameters allow us to return more than one value from a method call without having to wrap the results in struct/class.
The addition of the xxx.TryParse methods greatly simplified the coding necessary to convert between a string value (frequently from the UI) and a primitive type.
An example of what you might have had to write to achieve the same functionality is here:
/// <summary>
/// Example code for how <see cref="int.TryParse(string,out int)"/> might be implemented.
/// </summary>
/// <param name="integerString">A string to convert to an integer.</param>
/// <param name="result">The result of the parse if the operation was successful.</param>
/// <returns>true if the <paramref name="integerString"/> parameter was successfully
/// parsed into the <paramref name="result"/> integer; false otherwise.</returns>
public bool TryParse(string integerString, out int result)
{
try
{
result = int.Parse(integerString);
return true;
}
catch (OverflowException)
{
// Handle a number that was correctly formatted but
// too large to fit into an Int32.
}
catch (FormatException)
{
// Handle a number that was incorrectly formatted
// and so could not be converted to an Int32.
}
result = 0; // Default.
return false;
}
The two exception checks that are avoided here make the calling code much more readable. I believe that the actual .NET implementations avoid the exceptions altogether so perform better as well. Similarly, this example shows how IDictionary.TryGetValue(...) makes code simpler and more efficient:
private readonly IDictionary<string,int> mDictionary = new Dictionary<string, int>();
public void IncrementCounter(string counterKey)
{
if(mDictionary.ContainsKey(counterKey))
{
int existingCount = mDictionary[counterKey];
mDictionary[counterKey] = existingCount + 1;
}
else
{
mDictionary.Add(counterKey, 1);
}
}
public void TryIncrementCounter(string counterKey)
{
int existingCount;
if (mDictionary.TryGetValue(counterKey, out existingCount))
{
mDictionary[counterKey] = existingCount + 1;
}
else
{
mDictionary.Add(counterKey, 1);
}
}
And all thanks to the out parameter.
bool Int32.TryParse(String, out Int);
or something similar like Dictionary.TryGetValue.
But I would consider this one to be a not too good practice to employ it, of course, using those provided by API like the Int32 one to avoid Try-Catch is exceptions.
//out key word is used in function instead of return. we can use multiple parameters by using out key word
public void outKeyword(out string Firstname, out string SecondName)
{
Firstname = "Muhammad";
SecondName = "Ismail";
}
//on button click Event
protected void btnOutKeyword_Click(object sender, EventArgs e)
{
string first, second;
outKeyword(out first, out second);
lblOutKeyword.Text = first + " " + second;
}
Related
Returning multiple things from a method, involves either:
returning an object with properties OR
using the out keyword to simply modify incoming parameters
Is there a benefit to using one system or the other? I have been using objects, but just discovered the out keyword, so wondering if I should bother refactoring.
You shouldn't bother refactoring just to utilize out parameters. Returning a class or struct would be preferred as long as structure is reusable.
A common use for out parameters which I would suggest using is to return a status for a call with that is possible to fail. An example being int.TryParse.
It has the possibility of failing, so returning a bool makes it easy to determing whether or not you should use the out parameter.
Another possible solution to returning multiple values from a method would be to use a Tuple. They can return n number of results. E.g.
public Tuple<bool, bool, string> MyMethod()
{
return new Tuple<bool, bool, string>(false, true, "yep");
}
In general, if the object that you are returning is not used anywhere else outside of the return value of your method or a group of similar methods, it is a good indication that you should refactor. When you need to create a special class simply to be used as a return value of a method, it means that you are working around C#'s inability to return multiple values from a method, so the out keyword may be a very good option for you.
On the other hand, if you use the multi-part return value in other places, such as storing them in collections or passing as arguments to other methods, there's probably no need to refactor, because the return object is meaningful.
Compare these two methods:
interface DictionaryReturn<T> {
T Value {get;}
bool Success {get;}
}
...
class Dictionary<K,V> {
...
public DictionaryReturn<V> TryGetValue(K key) {
...
}
}
or
class Dictionary<K,V> {
...
public bool TryGetValue(K key, out V res) {
...
}
}
The first case introduces a special DictionaryReturn<T> class that provides the value and an indicator that the value was found in the dictionary. There is rarely, if ever, a reason to store or use DictionaryReturn<T> objects outside the call to TryGetValue, so the second option is better. Not surprisingly, it is the second option that the designers of the .NET collections library have implemented.
I prefer to use Object with properties. If you use out keyword, you need to define it in other line. It is not as clear as return Object;
The reason to use out keyword is to ensure that code inside the method always sets a value to the out parameter. It's a compile time check that what you intended to do in the function, you did do.
I've been wondering about this: would you support using simply an object as a parameter in your method? My reason behind doing this would be overloading. Currently, I'm trying to create a method that caters to many different datatypes: string, decimal, DateTime... the list goes on.
It's getting a bit messy though, so I was thinking of doing the following
public void GenericMethod(object val)
{
if (val is string)
// process as string
else if (val is decimal)
// process as decimal
else if (val is DateTime)
// do something for dt
else
// ...
}
What do you think of such a method? Would it incur unnecessary overhead? (during type checking) Have you implemented it? Tell me...
EDIT: Yeah, and just a sidenote, I'm kinda familiar with overloading. But it gets a little annoying when there are like more than 10 overloads...
Yes, that would work. However there are better ways of doing this.
Your best bet is to use overloads:
public void GenericMethod(string val)
{
// process as string
}
public void GenericMethod(decimal val)
{
// process as decimal
}
etc.
Whenever you use a is keyword in your code that's a huge hint that you're probably forgetting to use some important O.O. principles: overloads, subclasses, or the like.
Overloads aren't actually that annoying to work with, just to write. Remember, you're not coding this for yourself today, you're coding this for yourself three months from now when you have to read the code and figure out why the heck you did it that way, or where in the world that bug comes from.
Yet another reason to avoid the "switch on type" technique is for consistency with the .NET framework (and thus people's expectations). Follow Console.Write and the other wide variety of methods that are overridden within and under a given class.
I've been wondering about this: would you support using simply an object as a parameter in your method?
Very rarely. If there's a fixed set of types which are properly supported - and you'll throw an exception otherwise - then I'd use overloads.
If you can actually accept any type, and you'll handle a not-specially-supported type in some well-known way, then it's okay to accept object. That's what LINQ to XML does all over the place, and the result is a very clean API. I'd do it very carefully though - it's rarely a good idea.
And yes, there'd be an overhead. I wouldn't usually make that the basis of the decision though - the overhead will be small enough to be negligible in most cases. Design your API as cleanly as you can, then work out whether it's going to cause a bottleneck.
Yes, it would incur overhead for both type checking and boxing/unboxing the value type. I would recommend the overloads.
Another possibility, as long as you aren't doing a lot of math with the number, would be to make it a generic method. Arithmetic is rather difficult with generics though, as there are no constraints for value types which enables the use of operators.
No need of those!
Just declare as many methods with same name as you want and take each type as argument in each method.[This is called Overloading. e.g. You may have seen that +1 Overloads beside Methods, which implies that there is 1 more Method with same name but with different argument types]
Say Like this :
void Method(decimal d)
{
//Process Decimal
}
void Method(string s)
{
//Process String
}
By default, It will find its own method according to the Type.
There are cases where your approach makes sense. I've used it before, mostly when I have a bunch of processing that is the same for different data types.
But this is not overloading. Overloading would be to define different signatures for the same method name like this:
public void GenericMethod(string val)
{
// process as string
}
public void GenericMethod(decimal val)
{
// process as decimal
}
public void GenericMethod(DateTime val)
{
// do something for dt
}
// Etc.
And for some cases, this approach makes more sense.
Implementing many overloads one of them takes object is no problem. Take a look at Console.WriteLine overloads for example. http://msdn.microsoft.com/en-us/library/system.console.writeline.aspx However, take care that int for example can conflict with double:
int sum(int i, int j)
{
return i + j;
}
double sum(double i, double j)
{
return i + j;
}
object sum(object i, object j)
{
return i.ToString() + j.ToString();
}
==============================
static void Main()
{
sum(1, 2); // Error: ambigous call between `int` and `double` versions
sum(1.0, 2.0); // calls double version, although 1.0 and 2.0 are objects too
sum("Hello", "World"); // object
}
Assuming a method with the following signature
bool TryXxxx(object something, out int toReturn)
What is it acceptable for toReturn to be if TryXxxx returns false?
In that it's infered that toReturn should never be used if TryXxxx fails does it matter?
If toReturn was a nulable type, then it would make sense to return null. But int isn't nullable and I don't want to have to force it to be.
If toReturn is always a certain value if TryXxxx fails we risk having the position where 2 values could be considered to indicate the same thing. I can see this leading to potential possible confusion if the 'default' value was returned as a valid response (when TryXxxx returns true).
From an implementation point if view it looks like having toReturn be a[ny] value is easiest, but is there anything more important to consider?
I would explicitly document it as using the default value for the type (whatever that type is; so 0 in this case but default(T) in a more general case). There are various cases where the default value is exactly what you want if the value isn't present - and in that case you can just ignore the return value from the method.
Note that this is what methods like int.TryParse and Dictionary.TryGetValue do.
It could be default(int):
bool TryXxxx(object something, out int toReturn)
{
toReturn = default(int);
return false;
}
I would say default, but really it shouldn't matter. The convention with the TryX is that the caller should check the return value and only use the out parameter when the method returns true.
Basically it is something. I would document it as "not defined". Sensible values are:
default()
Minvalue, MaxCValue, NEWvalue (as new int ()), null
NAN value (Double.NaN)
But in general, I woul really say "not defined" and not give people something they may try to rely on.
1) Actually, I think it should not matter because you should always check the boolean result of those methods before processing the value. That's what the TryXXX methods are for.
2) However, in such cases, I always refer to the implementation in the .NET framework to guarantee consistency. And a quick look into Reflector shows that the Int32 type returns 0 if parsing failed:
internal static unsafe bool TryParseInt32(string s, NumberStyles style, NumberFormatInfo info, out int result)
{
byte* stackBuffer = stackalloc byte[1 * 0x72];
NumberBuffer number = new NumberBuffer(stackBuffer);
result = 0; // <== see here!
if (!TryStringToNumber(s, style, ref number, info, false))
{
return false;
}
if ((style & NumberStyles.AllowHexSpecifier) != NumberStyles.None)
{
if (!HexNumberToInt32(ref number, ref result))
{
return false;
}
}
else if (!NumberToInt32(ref number, ref result))
{
return false;
}
return true;
}
However, not knowing the implementation details, it might still happen that the parsing problem occurs when a value has already been assigned (partly). In this case, the value might no longer be 0. Therefore, you should always stick to "solution" 1)! :-)
gehho.
Prior to .net, a normal pattern was for TryXX methods to simply leave the passed-by-reference argument unmodified. This was a very useful pattern, since it meant that code which wanted to use a default value could do something like:
MyNum = 5;
TryParsing(myString, &myNum);
while code that didn't want to use a default value could use:
if (TryParsing(myString, &myNum))
{ .. code that uses myNum .. }
else
{ .. code that doesn't use myNum .. }
In the former usage, the calling code would have to ensure myNum was initialized before the call, but would not have to worry about the TryParsing return value. In the latter usage, the calling code would have to worry about the return value, but would not have to initialize myNum before the call. The TryParsing routine itself wouldn't have to worry about which usage was intended.
C# does not very well permit such a pattern, however, unless TryParsing is written in another language. Either TryParsing has to be written in such a way that the previous value of myNum will unconditionally be overwritten without having been examined, the caller must unconditionally initialize it, or different methods must be provided for the two scenarios. If the TryParsing method were written in some other language, it could in theory behave like the old-style methods (write the argument on success, and leave it alone if not) while still calling it an out parameter. I would not recommend this, however, because the quirky behavior would not be confined to that out parameter.
Consider, for example, that a method of that style used an argument of type fooStruct, and fooStruct had a constructor that looked like:
fooStruct(string st)
{
fooStruct.TryParse(st, out this);
}
The compiler would be perfectly happy with such a constructor, since it "definitely" writes this. On the other hand, if some other code does:
while(someCondition)
{
var s = new fooStruct(someString);
...
}
One might expect that s will either hold an initialized structure (if someString is valid) or be blank (if it isn't). Nothing about that code would suggest that s could kept its value between repetitions of the loop. Nonetheless, that is exactly what would likely happen.
I don't understand when an output parameter should be used, I personally wrap the result in a new type if I need to return more than one type, I find that a lot easier to work with than out.
I have seen method like this,
public void Do(int arg1, int arg2, out int result)
are there any cases where that actually makes sense?
how about TryParse, why not return a ParseResult type? or in the newer framework return a null-able type?
Out is good when you have a TryNNN function and it's clear that the out-parameter will always be set even if the function does not succeed. This allows you rely on the fact that the local variable you declare will be set rather than having to place checks later in your code against null. (A comment below indicates that the parameter could be set to null, so you may want to verify the documentation for the function you're calling to be sure if this is the case or not.) It makes the code a little clearer and easier to read. Another case is when you need to return some data and a status on the condition of the method like:
public bool DoSomething(int arg1, out string result);
In this case the return can indicate if the function succeeded and the result is stored in the out parameter. Admittedly, this example is contrived because you can design a way where the function simply returns a string, but you get the idea.
A disadvantage is that you have to declare a local variable to use them:
string result;
if (DoSomething(5, out result))
UpdateWithResult(result);
Instead of:
UpdateWithResult(DoSomething(5));
However, that may not even be a disadvantage, it depends on the design you're going for. In the case of DateTime, both means (Parse and TryParse) are provided.
I think out is useful for situations where you need to return both a boolean and a value, like TryParse, but it would be nice if the compiler would allow something like this:
bool isValid = int.TryParse("100", out int result = 0);
Well as with most things it depends.
Let us look at the options
you could return whatever you want as the return value of the function
if you want to return multiple values or the function already has a return value, you can either use out params or create a new composite type that exposes all these values as properties
In the case of TryParse, using an out param is efficient - you dont have to create a new type which would be 16B of overhead (on 32b machines) or incur the perf cost of having them garbage collected post the call. TryParse could be called from within a loop for instance - so out params rule here.
For functions that would not be called within a loop (i.e. performance is not a major concern), returning a single composite object might be 'cleaner' (subjective to the beholder). Now with anonymous types and Dynamic typing , it might become even easier.
Note:
out params have some rules that need to be followed i.e. the compiler will ensure that the function does initialize the value before it exits. So TryParse has to set the out param to some value even if parse operation failed
The TryXXX pattern is a good example of when to use out params - Int32.TryParse was introduced coz people complained of the perf hit of catching exceptions to know if parse failed. Also the most likely thing you'd do in case parse succeeded, is to obtain the parsed value - using an out param means you do not have to make another method call to Parse
Years late with an answer, I know.
out (and ref as well) is also really useful if you do not wish your method do instantiate a new object to return. This is very relevant in high-performance systems where you want to achieve sub microsecond performance for your method. instantiating is relatively expensive seen from a memory access perspective.
Definitely, out parameters are intended to be used when you have a method that needs to return more than one value, in the example you posted:
public void Do(int arg1, int arg2, out int result)
It doesn't makes much sense to use an out parameter, since you are only returning one value, and that method could be used better if you remove the out parameter and put a int return value:
public int Do(int arg1, int arg2)
There are some good things about out parameters:
Output parameters are initially considered unassigned.
Every out parameter must be definitely assigned before the method returns, your code will not compile if you miss an assignment.
In conclusion, I basically try use out params in my private API to avoid creating separate types to wrap multiple return values, and on my public API, I only use them on methods that match with the TryParse pattern.
Yes, it does make sense. Take this for example.
String strNum = "-1";
Int32 outNum;
if (Int32.TryParse(strNum, out outNum)) {
// success
}
else {
// fail
}
What could you return if the operation failed in a normal function with a return value? You most certainly could not return -1 to represent a fail, because then there would be no differentiation between the fail-return value and the actual value that was being parsed to begin with. This is why we return a Boolean value to see if it succeeded, and if it did then we have our "return" value safely assigned already.
Creating a type just for returning values sounds little painful to me :-)
First i will have to create a type for returning the value then in the calling method i have assign the value from the returned type to the actual variable that needs it.
Out parameters are simipler to use.
It does annoy me that I can't pass in null to the out parameter for the TryParse functions.
Still, I prefer it in some cases to returning a new type with two pieces of data. Especially when they're unrelated for the most part or one piece is only needed for a single operation a moment after. When I do need to save the resulting value of a TryParse function I really like having an out parameter rather than some random ResultAndValue class that I have to deal with.
If you always create a type, then you can end up with a lot of clutter in your application.
As said here, one typical use case is a TrySomething Method where you want to return a bool as an indicator for success and then the actual value. I also find that a little bit cleaner in an if-statement - all three options roughly have the same LOC anyway.
int myoutvalue;
if(int.TryParse("213",out myoutvalue){
DoSomethingWith(myoutvalue);
}
vs.
ParseResult<int> myoutvalue = int.TryParse("213");
if ( myoutvalue.Success ) {
DoSomethingWith(myoutvalue.Value);
}
vs.
int? myoutvalue = int.TryParse("213");
if(myoutvalue.HasValue){
DoSomethingWith(myoutvalue.Value);
}
As for the "Why not return a Nullable Type": TryParse exists since Framework 1.x, whereas Nullable Types came with 2.0 (As they require Generics). So why unneccessarily break compatibility or start introducing inconsistencies between TryParse on some types? You can always write your own extension Method to duplicate functionality already existing (See Eric Lipperts Post on an unrelated subject that includes some reasoning behind doing/not doing stuff)
Another use case is if you have to return multiple unrelated values, even though if you do that that should trigger an alarm that your method is possibly doing too much. On the other hand, if your Method is something like an expensive database or web service call and you want to cache the result, it may make sense to do that. Sure, you could create a type, but again, that means one more type in your application.
I use out parameters sometimes for readability, when reading the method name is more important than whatever the output of the method is—particularly for methods that execute commands in addition to returning results.
StatusInfo a, b, c;
Initialize(out a);
Validate(a, out b);
Process(b, out c);
vs.
StatusInfo a = Initialize();
StatusInfo b = Validate(a);
StatusInfo c = Process(b);
At least for me, I put a lot of emphasis on the first few characters of each line when I'm scanning. I can easily tell what's going on in the first example after acknowledging that some "StatusInfo" variables are declared. In the second example, the first thing I see is that a bunch of StatusInfo is retrieved. I have to scan a second time to see what kind of effects the methods may have.
I have several similar methods, say eg. CalculatePoint(...) and CalculateListOfPoints(...). Occasionally, they may not succeed, and need to indicate this to the caller. For CalculateListOfPoints, which returns a generic List, I could return an empty list and require the caller to check this; however Point is a value type and so I can't return null there.
Ideally I would like the methods to 'look' similar; one solution could be to define them as
public Point CalculatePoint(... out Boolean boSuccess);
public List<Point> CalculateListOfPoints(... out Boolean boSuccess);
or alternatively to return a Point? for CalculatePoint, and return null to indicate failure. That would mean having to cast back to the non-nullable type though, which seems excessive.
Another route would be to return the Boolean boSuccess, have the result (Point or List) as an 'out' parameter, and call them TryToCalculatePoint or something...
What is best practice?
Edit: I do not want to use Exceptions for flow control! Failure is sometimes expected.
Personally, I think I'd use the same idea as TryParse() : using an out parameter to output the real value, and returning a boolean indicating whether the call was successful or not
public bool CalculatePoint(... out Point result);
I am not a fan of using exception for "normal" behaviors (if you expect the function not to work for some entries).
Why would they fail? If it's because of something the caller has done (i.e. the arguments provided) then throwing ArgumentException is entirely appropriate. A Try[...] method which avoids the exception is fine.
I think it's a good idea to provide the version which throws an exception though, so that callers who expect that they will always provide good data will receive a suitably strong message (i.e. an exception) if they're ever wrong.
Another alternative is to throw an exception. However, you generally only want to throw exceptions in "exceptional cases".
If the failure cases are common (and not exceptional), then you've already listed out your two options. EDIT: There may be a convention in your project as how to handle such non-exceptional cases (whether one should return success or the object). If there is no existing convention, then I agree with lucasbfr and suggest you return success (which agrees with how TryParse(...) is designed).
If the failure is for a specific reason then I think its ok to return null, or bool and have an out parameter. If however you return null regardless of the failure then I don't recommend it. Exceptions provide a rich set of information including the reason WHY something failed, if all you get back is a null then how do you know if its because the data is wrong, you've ran out of memory or some other weird behavior.
Even in .net the TryParse has a Parse brother so that you can get the exception if you want to.
If I provided a TrySomething method I would also provide a Something method that threw an exception in the event of failure. Then it's up to the caller.
The model I've used is the same one MS uses with the TryParse methods of various classes.
Your original code:
public Point CalculatePoint(... out Boolean boSuccess);
public List CalculateListOfPoints(... out Boolean boSuccess);
Would turn into
public bool CalculatePoint(... out (or ref) Point CalculatedValue);
public bool CalculateListOfPoints(... out (or ref) List CalculatedValues);
Basically you make the success/failure the return value.
To summarise there are a couple of approaches you can take:
When the return type is a value-type, like Point, use the Nullable feature of C# and return a Point? (aka Nullable), that way you can still return null on a failure
Throw an exception when there's a failure. The whole argument/discussion regarding what is and isn't "exceptional" is a moot point, it's your API, you decide what's exceptional behaviour.
Adopt a model similar to that implemented by Microsoft in the base types like Int32, provide a CalculatePoint and TryCalculatePoint (int32.Parse and int32.TryParse) and have one throw and one return a bool.
Return a generic struct from your methods that has two properties, bool Success and GenericType Value.
Dependent on the scenario I tend to use a combination of returning null or throwing an exception as they seem "cleanest" to me and fit best with the existing codebase at the company I work for. So my personal best practice would be approaches 1 and 2.
It mostly depends on the behavior of your methods and their usage.
If failure is common and non-critical, then have your methods return a boolean indicating their success and use an out parameter to convey the result. Looking up a key in a hash, attempting to read data on a non-blocking socket when no data is available, all these examples fall in that category.
If failure is unexpected, return directly the result and convey errors with exceptions. Opening a file read-only, connecting to a TCP server, are good candidates.
And sometimes both ways make sense...
Return Point.Empty. It's a .NET design patter to return a special field when you want to check if structure creation was successful. Avoid out parameters when you can.
public static readonly Point Empty
A pattern that I'm experimenting with is returning a Maybe. It has the semantics of the TryParse pattern, but a similar signature to the null-return-on-error pattern.
I'm not yet convinced one way or the other, but I offer it for your collective consideration. It does have the benefit of not requiring a variable to defined before the method call to hold the out parameter at the call site of the method. It could also be extended with an Errors or Messages collection to indicate the reason for the failure.
The Maybe class looks something like this:
/// <summary>
/// Represents the return value from an operation that might fail
/// </summary>
/// <typeparam name="T"></typeparam>
public struct Maybe<T>
{
T _value;
bool _hasValue;
public Maybe(T value)
{
_value = value;
_hasValue = true;
}
public Maybe()
{
_hasValue = false;
_value = default(T);
}
public bool Success
{
get { return _hasValue; }
}
public T Value
{
get
{ // could throw an exception if _hasValue is false
return _value;
}
}
}
I would say best practice is a return value means success, and an exception means failure.
I see no reason in the examples you provided that you shouldn't be using exceptions in the event of a failure.
Using an exception is a bad idea in some cases (especially when writing a server). You would need two flavors of the method. Also look at the dictionary class for an indication of what you should do.
// NB: A bool is the return value.
// This makes it possible to put this beast in if statements.
public bool TryCalculatePoint(... out Point result) { }
public Point CalculatePoint(...)
{
Point result;
if(!TryCalculatePoint(... out result))
throw new BogusPointException();
return result;
}
Best of both worlds!
The bool TrySomething() is at least a practice, which works ok for .net's parse methods, but I don't think I like it in general.
Throwing an exception is often a good thing, though it should not be used for situations you would expect to happen in many normal situations, and it has an associated performance cost.
Returning null when possible is in most cases ok, when you don't want an exception.
However - your approach is a bit procedural - what about creating something like a PointCalculator class - taking the required data as parameters in the constructor? Then you call CalculatePoint on it, and access the result through properties (separate properties for Point and for Success).
You don't want to be throwing exceptions when there is something expected happening, as #Kevin stated exceptions are for exceptional cases.
You should return something that is expected for the 'failure', generally null is my choice of bad return.
The documentation for your method should inform the users of what to expect when the data does not compute.
We once wrote an entire Framework where all the public methods either returned true (executed successfully) or false (an error occurred). If we needed to return a value we used output parameters. Contrary to popular belief, this way of programming actually simplified a lot of our code.
Well with Point, you can send back Point.Empty as a return value in case of failure. Now all this really does is return a point with 0 for the X and Y value, so if that can be a valid return value, I'd stay away from that, but if your method will never return a (0,0) point, then you can use that.
Sorry, I just remembered the Nullable type, you should look at that. I am not too sure what the overhead is though.