Passing and changing values between methods in C Sharp


Here is a situation where you may want to use parameters in C#.

You have written your Main( ) method and SecondMethod( ).  In your main, you have a double variable varOne.  You would like for varOne to change and retain the value that results as it passes through SecondMethod( ).

You can accomplish this with either ref or out parameters.

The following code provides the use of ref and out parameters. 

class Program
    {
        public static void Main()
        {
            int testVal = 1;
            Console.WriteLine(“Initial Value of variable testValue: {0}”, testVal);
           
            Console.WriteLine(“Below is the default paramater value.”);
            DefaultParams(testVal);
            Console.WriteLine(“After returning from the default parameter method, “
                            + ” the test value is: {0}”, testVal);
            Console.WriteLine();
 
            Console.WriteLine(“Initial Value of variable testValue: {0}”, testVal);
            Console.WriteLine(“Below is the ref paramater value.”);
            RefParamType(ref testVal);
            Console.WriteLine(“After returning from the ref parameter method, “
                            + ” the test value is: {0}”, testVal);
            Console.WriteLine();
           
            //For out parameters, the variable does not have to be initialized.
            int testVal2;
 
            Console.WriteLine(“Below is the out paramater value.”);
            ParamOutType(out testVal2);
            Console.WriteLine(“After returning from the out parameter method, “
                            + ” the test value is: {0}”, testVal2);
            Console.WriteLine();
           
            Console.Read();
        }
 
        public static void DefaultParams(int testVal)
        {
            testVal = 7;
            Console.WriteLine(“Inside the DefaultParams method, the test value is: {0}”, testVal);
        }
 
        public static void RefParamType(ref int testVal)
        {
            testVal = 123;
            Console.WriteLine(“Inside the RefParamType method “
                                + ” the test value is: {0}”, testVal);
        }
 
        public static void ParamOutType(out int testVal2)
        {
            testVal2 = 444;
            Console.WriteLine(“Inside the ParamOutType method “
                                + “the test value is: {0}”, testVal2);
        }
 
    }

Leave a comment

Filed under Computer - Technical

Comment on this

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s