Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- /*
- Value1: 1
- Pass By Value: 5
- Value1: 1
- -------
- Value2: 1
- Pass By Ref: 5
- Value2: 5
- -------
- Ref1: 1
- Pass By Value: 5
- Ref1: 5
- -------
- Ref2: 1
- Pass By Ref: 10
- Ref2: 10
- */
- namespace RefVsVal
- {
- class Program
- {
- static void Main(string[] args)
- {
- int v1 = 1; //Value Type
- Console.WriteLine("Value1: {0}", v1);
- //Passing value by value
- ValByVal(v1);
- //Even though we've passed the value to a function and changed it, the value is unchanged.
- //This is because we created a copy!
- Console.WriteLine("Value1: {0}", v1);
- Console.WriteLine(); Console.WriteLine("-------"); Console.WriteLine();
- int v2 = 1; //Value Type
- Console.WriteLine("Value2: {0}", v2);
- //Passing value by referance
- ValByRef(ref v2);
- //This time we pass by value, so the change occurs here too!
- Console.WriteLine("Value2: {0}", v2);
- Console.WriteLine(); Console.WriteLine("-------"); Console.WriteLine();
- int[] r1 = new[] { 1 }; //Referance Type
- Console.WriteLine("Ref1: {0}", r1[0]);
- //passing referance by value
- RefByVal(r1);
- //We changed a value inside the array,
- //but not change the referance [to a new array]
- Console.WriteLine("Ref1: {0}", r1[0]);
- Console.WriteLine(); Console.WriteLine("-------"); Console.WriteLine();
- int[] r2 = new[] { 1 }; //Referance Type
- Console.WriteLine("Ref2: {0}", r2[0]);
- //passing referance by referance
- RefByRef(ref r2);
- //We changed the referance - in this case by pointing it to a new array!
- Console.WriteLine("Ref2: {0}", r2[0]);
- Console.ReadLine();
- }
- static void ValByVal(int i)
- {
- i = 5;
- Console.WriteLine("Pass By Value: {0}", i);
- }
- static void ValByRef(ref int i)
- {
- i = 5;
- Console.WriteLine("Pass By Ref: {0}", i);
- }
- static void RefByVal(int[] a)
- {
- a[0] = 5;
- Console.WriteLine("Pass By Value: {0}", a[0]);
- a = new[] { 10 };
- }
- static void RefByRef(ref int[] a)
- {
- a = new[] { 10 };
- Console.WriteLine("Pass By Ref: {0}", a[0]);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement