Reputation: 37
I'm programming in C# about 2 months, and I've been noticing to the fact that the only way a method will get a parameter by reference is when the method sets as a static method, and I don't understand the reason behind this situation. As example, in C++ we could just send parameters by reference to any kind of method we wanted to.
Thanks ahead :)
I'm adding a very simple code for those who asked for:
public void f(ref int num)
{
num++;
}
private static void Main(string[] args)
{
int a = 0;
f(ref a);
Console.WriteLine(a);
Console.Read();
}
the error I get:
An object reference is required for the non-static field, method, or property
now, I know that in C# almost everything that not int, string, double... and other built-in vars are send automatically by ref. I wonder why the method must be static in case of sending those vars by ref.
Upvotes: 0
Views: 157
Reputation: 18675
You are not able to use f
because it's an instance method and the Main
is a static one so you cannot call it from here without having an instance of the class that contains f
(I guess Program
).
You need to either create an instance of Program
:
this is exaclty the same as what the error message says:
An object reference is required for the non-static field, method, or property
so you create an object reference to Program
:
class Program
{
public void f(ref int num)
{
num++;
}
private static void Main(string[] args)
{
int a = 0;
var p = new Program();
p.f(ref a);
Console.WriteLine(a);
Console.Read();
}
}
or make the method static to be able to use it:
class Program
{
public static void f(ref int num)
{
num++;
}
private static void Main(string[] args)
{
int a = 0;
f(ref a); // is the same as: Program.f(ref a)
Console.WriteLine(a);
Console.Read();
}
}
The ref
keyword has nothing to do with it. It's all about how you call the method - via an object reference or as a static one without an object reference. Neither is better then the other. It's a design decision and each serves different puposes.
Upvotes: 1
Reputation: 149538
the only way a method will get a parameter by reference is when the method sets as a static method
That's incorrect. C# has a concept of Reference Types and Value Types, where both are passed by value, but that value differs. For reference types, the value that gets passed is the reference itself, where for value types it's a copy of the value.
If you want a value type by reference, you can use the ref
modifier in the methods signature:
public void M(ref int x)
Same goes for reference type, only for the fact that passing them by ref
will pass the current reference pointing to the data structure, and won't create a copy of that reference.
Upvotes: 1