Missing out variable initialization inside a function leads to exception
using System;
public class HelloWorld
{
public void Demo(out int a)
{
Console.WriteLine("Demo function");
}
public static void Main(string[] args)
{
HelloWorld h = new HelloWorld();
h.Demo(out int number);
Console.WriteLine ("Try programiz.pro");
}
}
The above code will create an exception saying "error CS0177: The out parameter 'a' must be assigned to before control leaves the current method"
using System;
public class HelloWorld
{
public void Demo(out int a)
{
int data = 10;
if(data==9)
{
a = 6;
Console.WriteLine("Inside if block");
}
Console.WriteLine("Demo function");
}
public static void Main(string[] args)
{
HelloWorld h = new HelloWorld();
h.Demo(out int number);
Console.WriteLine ("Try programiz.pro");
}
}
In the above code also the same exception will arise.Even though the initialization is made inside the if block,since the condition fails,it will not go inside the if block and initialization also will not happen.To avoid this, we can follow something I have mentioned in the below code
using System;
public class HelloWorld
{
public void Demo(out int a)
{
int data = 10;
a = 100;
if(data==10)
{
a = 6;
Console.WriteLine("Inside if block");
}
Console.WriteLine("Demo function");
}
public static void Main(string[] args)
{
HelloWorld h = new HelloWorld();
h.Demo(out int number);
Console.WriteLine ("Try programiz.pro");
}
}
In spite of the if block failing, since the initialization happens before the if block the above code will not throw any exception
Output
Inside if block
Demo function
Conclusion
It's mandatory to initialize the out variable inside the function.
Please do share your feedback!!! ☺️
Top comments (2)
Great 👍
Insightful 💡
Some comments may only be visible to logged-in visitors. Sign in to view all comments.