What is the difference between the ref and out keywords in C#?
Hello everyone! I started learning C# and came across the `ref` and `out` keywords. I understand that they both allow modifying passed variables inside a method, but the difference between them is not entirely clear to me.
Here's an example I wrote:
```csharp
public void TestRef(ref int x)
{
x = x * 2;
}
public void TestOut(out int x)
{
x = 10;
}
static void Main()
{
int a = 5;
int b; // Error: uninitialized variable for out
TestRef(ref a);
Console.WriteLine(a); // Outputs 10
TestOut(out b);
Console.WriteLine(b); // Outputs 10
}
```
I noticed that with `out` I cannot pass an uninitialized variable without an error, but I initialize it inside the method. And with `ref`, I must initialize the variable before the call. But this is not the only difference.
No answers yet.
Log in to leave an answer
Blogs