I'm switching to C# from C++ and I'm trying to learn the methods. Can you help me create a method that takes 2 variables as input from the user? In C++ it was pretty easy just making a void method and adding & before the variable's name like: void Input( int &a, int &b) which would save any changes in their value in the main function. Is there a way to do that in C#?
3 Answers
In C# you have two options for T &x of C++:
refparameters - these have the same capabilities as C++ reference parameters, andoutparameters - these allow passing data back from a method, but not into the method.
In your case, out is more appropriate, because it lets you pass variables that have not been previously assigned:
void Input( out int a, out int b) {
... // Read and assign a and b
}
You can call this method like this:
// In C# 7
Input(out int a, out int b);
// Prior to C# 7
int a, b;
Input(out a, out b);
Note that unlike C++ where taking reference is automatic, C# requires you to mark it with the keyword out.
4 Comments
out the right answer for OP's problem? He mentions that he wants to change variables from user input, which would implicate that the variables are already assigned. Hence, out would not work and ref should be used?out variables, so if you pass something by pointer or by reference, it's always a "change", not an initial assignment. C# gives you flexibility to decide whether you want the original value or not. A side effect of having ref would be the need to assign variables prior to making the call.You can achieve this using ref (C# Reference). This is equal to the C++ & references.
An example:
class RefExample
{
static void Method(ref int i)
{
// The following statement would cause a compiler error if i
// were boxed as an object.
i = i + 44;
}
static void Main()
{
int val = 1;
Method(ref val);
Console.WriteLine(val);
// Output: 45
}
}
Worth to mention that the usage of ref in C# should be pretty rare unlike in C++. Please refer to Jon Skeet's article about parameter passing.
Comments
In C# you can pass an argument by reference with the ref keyword. So you can define your method like:
public void Input (ref int foo, ref int bar) {
foo = 14;
bar = 25;
}
You call the method with the ref keyword as well:
int a = 0;
int b = 0;
Input(ref a, ref b);
// now a = 14 and b = 25
You this mention pass-by-reference explicitly (but the advantage is that syntactically it is clear that this is pass-by-reference).
&is arefin C#.