In my previous article, we discussed about the concept of local functions in C# 7.0. In this article, we will see another feature related to the use of out type variables.
Out variables are not new in C# and provide a big advantage of how we can return multiple values from a method. However, in order to pass a out type variable as a method parameter, we have to declare it first and then pass it into the method parameter, with out keyword. Something like the following:
- static void Main(string[] args)
- {
- int userId;
- string userName;
- GetDetails(out userId, out userName);
- Console.ReadKey();
- }
- public static void GetDetails(out Int32 UserId, out string Username)
- {
- UserId = 12;
- Username = "Test User";
- }
However, in C# 7.0, we can declare the variable at the time of passing it as a method parameter, when method is being called. This means the following code will work fine in C# 7.0.
- static void Main(string[] args)
- {
- GetDetails(out int userId, out string userName);
- Console.ReadKey();
- }
- static void Main(string[] args)
- {
- GetDetails(out var userId, out var userName);
- Console.ReadKey();
- }
Hope you enjoyed reading it. Happy coding...!!!
No comments:
Post a Comment