Using Pointer Type C# with Example



Using Pointer Type C# with Example

 	using System;

	namespace CSharpClass
	{
		class UsingPointers
		{
			unsafe public static void UnsafeSwap(int* i, int* j)
			{
				int temp = *i;
				*i = *j;
				*j = temp;
			}

			public static void SafeSwap(ref int i, ref int j)
			{
				int temp = i;
				i = j;
				j = temp;
			}

			static void Main()
			{
				int x=10, y=20;
				Console.WriteLine("Swapping via Safe Code");
				Console.WriteLine("Before Swapping: X={0} and Y={1}", x, y);
				SafeSwap(ref x,ref y);
				Console.WriteLine("After Swapping: X={0} and Y={1}", x, y);
				
				int p=10, q=20;
				Console.WriteLine("\nSwapping via Unsafe Code");
				Console.WriteLine("Before Swapping: P={0} and Q={1}", p, q);
				unsafe
				{
					UnsafeSwap(&p,&q);
				}
				Console.WriteLine("After Swapping: P={0} and Q={1}", p, q);

			}
		}
	} 

0 Comment's

Comment Form