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?
C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...
In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.
C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.
C is more difficult to learn than JavaScript, but it's a valuable skill to have because most programming languages are actually implemented in C. This is because C is a “machine-level” language. So learning it will teach you how a computer works and will actually make learning new languages in the future easier.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With