Friday, March 9, 2012

UnSafe KeyWord in c#


UnSafe Code in C# :


Pointer : Pointer is a variable which holds the address of another variable i.e; which is not hold the direct value it holds address of the variable.

Pointers in c# is achieved by using the Unsafe keyword. Unsafe code is code which does not executed under the full management of common language runtime (CLR).Unsafe code is also called as Unmanaged code because it is not execute under the full management of CLR.

Suppose if you want to declare a Method or block as a Unmanaged code then need to declare method with “Unsafe” Keyword.

Syntax : Public unsafe <returntype> <MethodName>(<Methodarguments>)

The following program will demonstrate the unsafe keyword in c# :
Open Microsoft visual studio 2010 and create a console application. Copy the following code as new class :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BloggerExamples
{
    class MyClass
    {
        public unsafe void DemonUnsafe()
        {

        int a = 10;
        int b = 30;
        int* ptr1 = &a;
        int* ptr2 = &b;
        Console.WriteLine((int)ptr1);
        Console.WriteLine((int)ptr2);
        Console.WriteLine(*ptr1);
        Console.WriteLine(*ptr2);

        }
    }
   
    class UnsafeExample
    {
        static void Main(string[] args)
        {
            MyClass mc = new MyClass();
            mc.DemonUnsafe();
            Console.Read();

        }
    }
}


If you build the application you will able to see the following error : 

Error   1        Unsafe code may only appear if compiling with /unsafe 
 
To Remove the Error go to console application on the solution explorer and right click --> select properties --> select build option (from Left Side panel) --> check the checkbox saying Allow Unsafe coding --> save the files and build it.Now you won’t find the above error.


The following out put will give the above code : 


Interview questions on Unsafe Code :

1) Can we use pointer in c# ? View Answer
2) Why we use pointer in C#.NET with Unsafe keyword? View Answer

No comments:

Post a Comment