C# out parameters vs returns - c#

So I am new to C# and I am having difficulty understanding out. As opposed to just returning something from a function
using System;
class ReturnTest
{
static double CalculateArea()
{
double r=5;
double area = r * r * Math.PI;
return area;
}
static void Main()
{
double output = CalculateArea();
Console.WriteLine("The area is {0:0.00}", output);
}
}
compare to this
using System;
class ReturnTest
{
static void CalculateArea(out double r)
{
r=5;
r= r * r * Math.PI;
}
static void Main()
{
double radius;
CalculateArea(out radius);
Console.WriteLine("The area is {0:0.00}",radius );
Console.ReadLine();
}
}
The first one is how I would generally do it. Is there a reason why I may want to use out instead of just a return statement? I understand that ref allows for 2 way communication, and that I generally shouldn't use ref unless the function is doing something with the variable I am sending it.
However is there a difference between out and return statements, like shown above? Syntax-wise is there a reason to favor one or the other?

A good use of out instead of return for the result is the Try pattern that you can see in certain APIs, for example Int32.TryParse(...). In this pattern, the return value is used to signal success or failure of the operation (as opposed to an exception), and the out parameter is used to return the actual result.
One of the advantages with respect to Int32.Parse is speed, since exceptions are avoided. Some benchmarks have been presented in this other question: Parsing Performance (If, TryParse, Try-Catch)

The out keyword is mostly used when you want to return more than one value from a method, without having to wrap the values in an object.
An example is the Int32.TryParse method, which has both a return value (a boolean representing the success of the attempt), and an out parameter that gets the value if the parsing was successful.
The method could return an object that contained both the boolean and the integer, but that would need for the object to be created on the heap, reducing the performance of the method.

Only time I tend to use out is when I need multiple things returned from a single method. Out lets you avoid wrapping multiple objects into a class for return. Check out the example at the Microsoft Out page.

You can have multiple out parameters, so if you need to return multiple values, it's a bit easier than creating a special class for your return values.

When one variable is concerned out and return are OK. But what if you wanted to return more than 1 values? Out helps in that.
static void CalculateArea(out double r, out double Foo)
{
//Can return 2 values in terms of out variables.
}
static double CalculateArea(double r)
{
// Will return only one value.
}

Related

confused about return methods and voids in C#

Want feedback if i`m correct here?
Use void if you are not returning anything in a method,
otherwise
Name your data types used in the method criteria before method name.
use Return in the method before the calculation or output.
So something like this.
static int MyMethod(int x)
{
return 5 + x;
}
static void Main(string[] args)
{
Console.WriteLine(MyMethod(3));
}
// Outputs 8 (5 + 3)
What if my method has ints and doubles?
Do I write as follows? (another words do I have to mention every type i`m using prior to the method name?
static int double myMethod (int x, double y)
Even with that I dont know when is a method void? It seems my methods all return values.
Isnt the following returning the values of the arguments? So why should I label it void?
static void MyMethod(string fname, int age)
{
Console.WriteLine(fname + " is " + age);
}
static void Main(string[] args)
{
MyMethod("Liam", 20);
MyMethod("Jenny", 25);
MyMethod("Tom", 31);
}
I can only think that a void means there is no new calculation being done in the actual method body, passing arguments into a method and spitting them out for user viewing does not mean its "returning a value", I dont know what i`m talking about.
Let's be completely clear about what these bullets mean.
Use void if you are not returning anything in a method, otherwise
In this context, "return" means that the method provides an output that can be assigned to a variable by the caller. For example
int Return10()
{
return 10;
}
...allows the caller to do this:
int x = Return10();
Console.WriteLine(x); //Outputs "10"
A method should "return" void when its results cannot be assigned. For example, if the results are printed on the screen.
void Print10()
{
Console.WriteLine("10"); //Prints 10 to the screen
}
...which allows the caller to do this:
Print10();
You cannot assign it because it doesn't return anything. This doesn't work:
int x = Print10(); //Compiler error
Name your data types used in the method criteria before method name.
A method can return exactly one value or object. So "types" here is wrong. You can only specify one type.
Use return in the method before the calculation or output.
This is a little misleading. The return keyword should be followed by an expression which can be assigned.
int Return10()
{
return 10 + 10; //Is okay because it's an expression and could be assigned
}
int Return10()
{
var x = 10 + 10;
return x; //This is also okay; in fact it does exactly the same thing as the previous example
}
int Return10()
{
return Console.WriteLine("10"); //Compiler error; can't be assigned to anything.
}
By the way, a method can also output something and return it:
int WriteAndReturn10()
{
int x = 10;
Console.WriteLine(x);
return x;
}
I am going to address the following
What if my method has ints and doubles? Do I write as follows?
(another words do I have to mention every type i`m using prior to the
method name?
There are no built in ways or syntax to return more than one type from a method as the return parameter.. This is basically historical and has been this way since dinosaurs roamed the earth.
However, there are lots of options that achieve the same result. For instance, you could use a custom struct, you could use out parameters, you could use a class, or a delegate parameter of some kind. However, a modern succinct approach might be to use a Value Tuple:
static (int someInt, double someDouble) myMethod (int x, double y)
{
return (x,y);
}
Fun Fact : even though this looks like you a returning more than one type, you are actually just invoking a special syntax that wraps your return parameters in a single type of struct
Usage
var result = myMethod(1,2.2);
Console.WriteLine(result.someInt);
Console.WriteLine(result.someDouble);
Or if you want to get fancy, you can use the newer deconstructed syntax
var (someInt, someDouble) = myMethod(1,2.2);
Console.WriteLine(someInt);
Console.WriteLine(someDouble);
Additional Resources
return (C# Reference)
Methods (C# Programming Guide)
Tuple types (C# reference)
out parameter modifier (C# Reference)
ref (C# Reference)
Using Delegates (C# Programming Guide)

Trying to parse a string in C# using the TryParse helper method

I'm trying to parse user entered text into a float so that I can perform some wicked awesome math on the result. The result being the numberA variable at the end there. This is how I'm parsing the string into a float:
numberAString = GUI.TextField(new Rect(25, 100, 100, 25), numberAString.ToString());
bool ParsableCheckA = float.TryParse(numberAString, out numberA);
I eventually multiply numberA by another float later. I'm handling text that won't parse with a simple error message later. Couple things that bug me:
1) Why do I need to use numberAString in the TryParse parameters instead of its value? Why can't I just drop GUI.Textfield etc. into that slot? Why do I need to break this up over two lines of code?
2) I get a warning that I never use ParsableCheckA (which is true). But without it, I can't seem to use that Tryparse helper, no? Is there a way to eliminate the need for that bool? Thanks.
TryParse() Metod and its usage is rather straighforward, as shown in the following example:
double _dblOriginal;
_dblOriginal=3.141592;
string _str;
_str = _dblOriginal.ToString();
double _dblParsed;
bool _parseOK= TryParse(_str, out dblParsed);
More details in: http://msdn.microsoft.com/en-us/library/system.double.tryparse%28v=vs.110%29.aspx
Note: make sure that in your example the string numberAString you pass to the TryParse() method contains a valid number.
Also, FYI: TryParse() method has some performance benefits compare to just Parse() method because it does not throw an exception if parsing fail (instead you just check the bool result value).
Hope this will help. Regards,
(1) numberAString (see GUI.TextField) is a string, so you can use it directly in the TryParse() call.
(2) TryParse() is designed to return a boolean value so you can check for errors and take action. However, you aren't required to assign the return value. You can us it like this and simply accept the default value (0.0) assigned to the out parameter:
float.TryParse(numberAString, out numberA);
In this case you would not be able to distinguish between an invalid entry and a value that parsed correctly as zero.
I personally create an extension method to make my number parsing easier. If performance is critical, then this may not be a good idea (because for valid floats, you'll be essentially converting them twice). But I don't the effect on performance is much more than negligible.
public static class NumberExtensions
{
//Test if the text represents a valid float.
public static bool IsFloat(this string text)
{
float dummy = 0;
return Float.TryParse(text, out dummy);
}
//Convert the text to a float. Will throw exception if it's not a valid float.
public static float ToFloat(this string text)
{
float number = Float.Parse(text);
return number;
}
}
Usage...
string text = "123";
if(text.IsFloat())
{
//text must be a valid float
float myfloat = text.ToFloat();
}
else
{
//text isn't a valid float
}
You have to remember to test if it's a float by calling the IsFloat() extension method, but it's much easier for me to think of it conceptually like this rather than using out variables, which some think is a bad idea.

Inline use of function returning more than one value in C#

I am used to using functions that return a single value "in-line" like so:
Label1.Text = firstString + functionReturnSecondString(aGivenParameter);
Can this be done for a function that returns two values?
Hypothetical example:
label1.Text = multipleReturnFunction(parameter).firstValue
I have been looking into returning more than one value and it looks like the best options are using a tuple, struct, or an array list.
I made a working function that retuns a struct. However the way I got it to work I need to first call the function, then I can use the values. It doesn't seem possible to make it happen all on the same line without writing another function.
multipleReturnFunction(parameter);
Label1.Text = firstString + classOfStruct.secondString;
I haven't made a function that returns a tuple or array list yet, so I'm not sure. Is it possible to call those functions and reference the return values "inline"?
I appreciate your feedback.
I have a grotty hack for exactly this type of scenario - when you want to perform multiple operations on the return value without defining an extra variable to store it:
public static TResult Apply<TInput, TResult>(this TInput input, Func<TInput, TResult> transformation)
{
return transformation(input);
}
... and here's the reason it came about in the first place:
var collection = Enumerable.Range(1, 3);
// Average reimplemented with Aggregate.
double average = collection
.Aggregate(
new { Count = 0, Sum = 0 },
(acc, i) => new { Count = acc.Count + 1, Sum = acc.Sum + i })
.Apply(a => (double)a.Sum / (double)a.Count); // Note: we have access to both Sum and Count despite never having stored the result of the call to .Aggregate().
Console.WriteLine("Average: {0}", average);
Needless to say this is better suited for academic exercises than actual production code.
Alternatively, use the ref or they out keyword.
Example:
int a = 0, b = 0;
void DoSomething(ref int a, ref int b) {
a = 1;
b = 2;
}
Console.WriteLine(a); // Prints 1
Console.WriteLine(b); // Prints 2
It's not inline and I personally would consider a class or a struct before using the ref or the out keyword. Let's consider the theory: when you want to return multiple things, you have in fact an object that has multiple properties which you want to make available to the caller of your function.
Therefore it is much more correct to actually create an object (either by using a class or a struct) that represents what you want to make available and returning that.
The only time I use the ref or the out keyword is when using DLL imports because those functions often have pointers as their calling arguments and I personally don't see any benefit in using them in your typical normal application.
To do this inline, I think you would have to have another method that takes your struct and gives you the string you are looking for.
public string NewMethod(object yourStruct)
{
return string.Format("{0} {1}", yourStruct.value1, yourStruct.value2);
}
Then in the page, you do this:
Label1.Text = NewMethod(multipleReturnFunction(parameter));
C# doesn't have Inline functions, but it does support anonymous functions which can be closures.
With these techniques, you can say:
var firstString=default(String);
var secondString=default(String);
((Action<String>)(arg => {
firstString="abc"+arg;
secondString="xyz";
}))("wtf");
label1.Text=firstString+secondString;
Debug.Print("{0}", label1.Text);
((Action<String>)(arg => {
firstString="123"+arg;
secondString="456";
}))("???");
label1.Text=firstString+secondString;
Debug.Print("{0}", label1.Text);
or name the delegate and reuse it:
var firstString=default(String);
var secondString=default(String);
Action<String> m=
arg => {
firstString="abc"+arg;
secondString="xyz";
};
m("wtf");
label1.Text=firstString+secondString;
Debug.Print("{0}", label1.Text);
m("???");
label1.Text=firstString+secondString;
Debug.Print("{0}", label1.Text);
So, do you really need a method returns multiple values?
Each method can return only one value. Thats how methods defined in .NET
Methods are declared in a class or struct by specifying the access
level such as public or private, optional modifiers such as abstract
or sealed, the return value, the name of the method, and any method
parameters
If you need to return more than one value from method, then you have three options:
Return complex type which will hold all values. That cannot help you in this case, because you will need local variable to store value returned by method.
Use out parameters. Also not your case - you will need to declare parameters before method call.
Create another method, which does all work and returns single value.
Third option looks like
Label1.Text = AnotherMethod(parameters);
And implementation
public string AnotherMethod(parameters)
{
// use option 1 or 2 to get both values
// return combined string which uses both values and parameters
}
BTW One more option - do not return values at all - you can use method which sets several class fields.

How to properly put statements inside a try-catch block?

I need to execute a lot of statements, one after the other, and I need that when a sigle statement throws an exception the flow of the program continues executing the next statement, for example:
double a = Double.Parse("2.5");
double b = Double.Parse("ADFBBG");
Geometry g = Geometry.Parse("M150,0L75,200 225,200z");
All statements have to be executed, so I need a sort of try-catch blocks in cascade:
double a, b;
Geometry g;
try
{
a = Double.Parse("2.5");
}
catch
{}
try
{
b = Double.Parse("ADFBBG");
}
catch
{}
try
{
g = Geometry.Parse("M150,0L75,200 225,200z");
}
catch
{}
Obviously this is not the most elegant way to write my program. Is there a better way (more elegant, that does not reduce significantly the performance)?
I tried using the Func<TResult> delegate in such a way:
I wrote the following method:
T Try<T>(Func<T> func)
{
try
{
return func();
}
catch
{
return default(T);
}
}
So I can use it like this:
double x = Try(() => Double.Parse("77"));
Geometry g = Try(() => Geometry.Parse("M150,0L75,200 225,200z"));
Other solutions?
Use Double.TryParse.
It returns a value indicating whether the conversion was successfull. So you can use it the following way:
double converted;
bool success = Double.TryParse(value, out converted);
if (success)
{
// Do whatever you want
// The converted value is in the variable 'covnerted'
}
It seems that you don't care about which parse failed but just need a default value is case of failure? If so init your vars first to defaults then parse in a single try-catch:
double a=0.0, b=0.0;
Geometry g = new Geometry();
try
{
a = Double.Parse("2.5");
b = Double.Parse("ADFBBG");
g = Geometry.Parse("M150,0L75,200 225,200z");
}
catch
{
//At least mark that conversion was not succesful
}
Try-catch will only give you a performance hit when an exception is thrown. If all is well the impact of try-catch is minimal. see this question
A bit more elegant then your posted code but at least more concise.
Alternative with using TryParse
double a=0.0, b=0.0;
Geometry g = new Geometry();
Double.TryParse("2.5", out a);
Double.TryParse("ADFBBG", out b);
Geometry.TryParse("M150,0L75,200 225,200z", out g);
But there is a caveat: Geometry doesn't has TryParse implemented... (assuming that you use System.Windows.Media.Geometry)
That brings me to the point:
use your Try<> func, doens't reduce overhead but is clean
validate the string first. Removes the overhead of try but introduces runtime overhead on parsing.
Either way: validating userinput has it costs.
In answer to the main question: How to properly put statements inside a try-catch block?
If you don't care about which statement fails: 1 try-catch.
However: If the first statement fails, the other statement won't get executed. But, your system is already in in failed/corrupted state. Would further processing result in a correct result? (doubt it)
TryParse is more preferable, because you've no performance penalty on throwing and catching exception.
And one more inaccuracy in the above code - no difference between parsed "0" and default(T).
Code's more fast than yours
public static class StringExt
{
public static double ParseDouble(this string value)
{
double result;
Double.TryParse(value, out result);
return result;
}
}
I have answered a similar question a few days ago. If you have a collection of string values, you can use the power of extension methods to do just that.
static public IEnumerable<double> ConvertToDouble(this IEnumerable<string> source)
{
double x = 0;
var result = source.Where(str => Double.TryParse(str, out x))
.Select (str => x);
return result;
}
So put everything in a collection and use .AsEnumerable() followed by ConvertToDouble() extension method. Everything which cannot be parsed, will be ignored without an exception and the result is of type IEnumerable<Double>
Original answer: Convert List<string> to List<int> in C#
/edit: does the downvoter care to explain? The OP has not clarified, why he wants to use try catch and has not explained what has to be done in case of an exception. Hance I assume he does not want to do anything in case an exception is raised.

TryParse pattern / Non Default constructor with readonly fields

How do people generally implement a parsing constructor with the TryParse pattern, when they have readonly backing fields, and a non default constructor, that would normally do the parsing?
Below is a contrived example of what I'm talking about, and the pattern I've settled on, but it seems clunky. In reality some of the types have a large number of properties. Sure, I can create a method that would take n ref arguments, do the parsing, and wire them up that way, but having a method with 15 arguments in some cases is a pain/smelly also.
The idea of two constructors, plus having to copy the result of the try parse to the readonly fields in the parsing constructor smells a little.
Anyone else have a better pattern?
Edit: Provide some more context
What I'm attempting to do, is refactor a large(ish) codebase, which has many types like the example below, where there is parsing of string arguments supplied to the constructor. Right now, all of the code uses constructor parsing, and the logic for this parsing is all done in the constructor. Messy and troublesome.
First thing I want to do, is move this code out of the constructor, into a factory method, (TryParse), but preserve the constructor signature, so I dont have lots of changes to the codebase. Long term, something better can be done when there is time.
Currently, the difficulty is keeping the constructure signature intact for the existing code, while allowing new code to use the TryParse pattern, and keep the readonly fields. If I relaxed the readonly fields, the entire process would be easier, but I'd rather not.
public class Point
{
private readonly float x, y;
public float X { get { return x; } }
public float Y { get { return y; } }
public Point(string s)
{
Point result;
if (TryParse(s, out result))
{
this.x = result.x;
this.y = result.y;
}
else
{
throw new System.ArgumentException("cant parse");
}
}
private Point(float x,float y) // for the sake of the example, this wouldnt have any use as public
{
this.x = x;
this.y = y;
}
public static bool TryParse(string s,out Point result)
{
var numbers = s.Split(',');
if(numbers.Length == 2)
{
result = new Point(float.Parse(numbers[0]),float.Parse(numbers[0]));
return true;
}
else
{
result = null;
return false;
}
}
}
Your current approach doesn't really work - because float.Parse can throw an exception. I'd use something like:
public static bool TryParse(string s, out Point result)
{
var numbers = s.Split(',');
if (numbers.Length == 2)
{
float x, y;
if (float.TryParse(numbers[0], out x) &&
float.TryParse(numbers[1], out y))
{
result = new Point(x, y);
return true;
}
}
result = null;
return false;
}
As StriplingWarrior says, I'd get rid of the parsing constructor to start with - if you're using TryParse anyway, add a Parse method too.
The idea of two constructors, plus having to copy the result of the try parse to the readonly fields in the parsing constructor smells a little.
Well with this approach, you only need one constructor - but what's wrong with passing values to a constructor and it copying them into the object? That seems natural to me.
Alternatively, you could use the approach we use in Noda Time where you create a whole separate object responsible for parsing and formatting, and a ParseResult<T> type which is able to represent the success/failure of a parse, while retaining the ability to throw an exception with meaningful information about the failure. Personally I find it a lot nicer than the BCL pattern, although arguably I'm biased :)
I usually try to avoid parsing constructors. There is a popular sentiment that constructors should do as little as possible, and usually only take arguments that get stored directly into fields for later use. If you want to parse a string, that's not the responsibility of the constructor.
You have a TryParse method that follows the typical expected pattern for C#/.NET apps. Make the changes that Jon Skeet recommends, then expect your users to call that method directly if they want to parse a string to a Point.

Categories