The main purpose of "Dot Net Labs" provide the dot net program. You can learn dot net, .Net Core, C#, SQL, Linq step-by-step.

Tuesday, 16 May 2023

What is the difference between ref and out keywords in C#?


The ref and out keywords in C# are used to pass arguments to methods by reference instead of by value. Both ref and out parameters are treated the same at compile-time but different at run-time. However, there is a several differences between the ref and out. We will see difference in the example.


ref Example

using System;

using System.Collections.Generic;

using System.Linq;

 

namespace SoftwareEngineerDotNet

{

    class Program

    {

        static void Main(string[] args)

        {

            // Assign string value

            //parameters should initialize before it pass to ref

            string name = "Amit";

 

            //Pass as a reference parameter

            SetName(ref name);

 

            //Display name

            Console.WriteLine(name);

        }

 

        static void SetName(ref string name2)

        {

            Console.WriteLine(name2);

 

            //Assign the new value

            //Not necessary to initialize the value of a parameter before returning

            name2 = "Kumar";

        }

    }

}

 

Output:

 

Amit

Kumar

out keyword

using System;

using System.Collections.Generic;

using System.Linq;

 

namespace SoftwareEngineerDotNet

{

    class Program

    {

        static void Main(string[] args)

        {

            //Declaring variable without assigning value

            int salary;

 

            //Pass salary variable to method with out keyword

            GetSalary(out salary);

 

            //Display name

            Console.WriteLine("Sum of salary: {0}", salary);

        }

 

        //Method will return the value

        public static void GetSalary(out int salary)

        {

            salary = 5000;

            salary += salary;

        }

    }

}

 

Output:

 

Sum of salary: 10000

 

0 comments:

Post a Comment

Do not enter spam link

Popular Posts