Is there a way to create and return new variables from a method in C #?
Basically, like using the out keyword. But the problem is with the out keyword, you still need to declare the variable outside of the method call, for example:
double result;
Double.TryParse ( "76", out result );
where i need something like:
Double.TryParse ( "76", out result );
and there I get a new variable named result.
Is there a way to do this (using or not)?
source to share
A variable must be declared before using it, and a method with multiple parameters gets smelly. Out parameters especially.
I think what you want to do is declare a class containing five or six variables and pass that as an argument to the method:
class Args
{
public int One { get; set; }
public int Two { get; set; }
public int Three { get; set; }
public int Four { get; set; }
public int Five { get; set; }
}
The method then takes it as an argument:
public void Foo(Args args)
{
// Modify members of args here.
}
And use it like this:
Args args = new Args();
Foo(args);
// Do stuff with results in args.
source to share
live on the stack, not the heap, so the notion of calling a function to create new variables - while an interesting idea and not impossible in other languages โโ- implies that you don't understand the difference between a variable and an object in C #.
- variable storage is allocated on the stack, and the variable exists only for the duration of the execution of the function declaring the variable
this differs from a "member variable" which is a field owned by an object.
the 'out' keyword in C # means that the variable will be passed to the function "by reference" and the function is expected to (should) set the value of the variable.
in general, "out" parameters should be avoided; if you need to pass multiple values โโfrom a function, they probably belong to the missing object!
EDIT: In the C # parameter, an 'out' is similar to the 'ref' parameter in that they are both call-by-reference parameters, as opposed to the more typical "per-value" parameter.
source to share