How Unsafe is C#'s Unsafe Block? | CodeGuru

How Unsafe is C#’s Unsafe Block?

Environment: C# C# is the language of .NET. Microsoft believes this is the most powerful and safest language around. Yaaa. It is a “remix” of Java with certain features such as Unsafe blocks to boost performance. But, there is the hack; Microsoft has tried to make conflicting goals meet with C# an example of which […]

Written By
CodeGuru Staff
CodeGuru Staff
Aug 6, 2003
1 minute read
CodeGuru content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More

Environment: C#

C# is the language of .NET. Microsoft believes this is the most powerful and safest language around. Yaaa. It is a “remix” of Java with certain features such as Unsafe blocks to boost performance. But, there is the hack; Microsoft has tried to make conflicting goals meet with C# an example of which are unsafe blocks. C#’s unsafe blocks can render code that is as dangerous as C++. To see how, let’s look at the following code:

public class AClass {
  public int aValueMember=0;
  private string _aRefMember="default";
  public string aRefMember
  {
    get {return _aRefMember;}
  }
}

Now, looking at this class, it may seem that the instance member _aRefMember’s value=”default” cannot be changed. If you think so, picture this…

public class Client {
  [STAThread]
  public static void Main(string[] arg) {
    AClass obj=new AClass();
    Console.WriteLine("Before Unsafe Block.................");
    Console.WriteLine("obj.aRefMember: ="+obj.aRefMember);
    unsafe {
      char* arrayPtr;
      fixed(int* ptr=&obj.aValueMember) {
        arrayPtr=(char*)(*(ptr-1));    // taking the address of
                                       // obj._aRefMember,
                                       // subtracting 1 becuase
                                       // the heap and stack grow
                                       // downwards in C#
                                       // this can be even nastier
                                       // *(ptr-1)=-1;
        arrayPtr[6]='D';               // first 6 bytes of the
                                       // string contains
                                       // information such as the
                                       // length of the string...
        arrayPtr[7] ='E';
        arrayPtr[8] ='F';
        arrayPtr[9] ='A';
        arrayPtr[10]='U';
        arrayPtr[11]='L';
        arrayPtr[12]='T';
      }

    }
    Console.WriteLine("After Unsafe Block.....");
    Console.WriteLine("obj.aRefMember: ="+obj.aRefMember);
  }
}

The Value of “obj.aRefMember” changed to “DEFAULT” from “default” ….. But, that’s not all. You also can make the referance _aRefMember point to any location with this code:

  *(ptr-1)=XX;    // XX is any address be it legal or illegal

One thing that is encouraging is that if you assign an illegal address to the referance, the application will not crash but the CLR will raise a NullPointerException.

What the above code illustrates is that C#’s unsafe mechanism makes it as unsafe as C++. In principle, you can do many of the nasty things with it that you could do with C++, such as playing with the vTable and so forth.

CodeGuru Logo

CodeGuru covers topics related to Microsoft-related software development, mobile development, database management, and web application programming. In addition to tutorials and how-tos that teach programmers how to code in Microsoft-related languages and frameworks like C# and .Net, we also publish articles on software development tools, the latest in developer news, and advice for project managers. Cloud services such as Microsoft Azure and database options including SQL Server and MSSQL are also frequently covered.

Property of TechnologyAdvice. © 2026 TechnologyAdvice. All Rights Reserved

Advertiser Disclosure: Some of the products that appear on this site are from companies from which TechnologyAdvice receives compensation. This compensation may impact how and where products appear on this site including, for example, the order in which they appear. TechnologyAdvice does not include all companies or all types of products available in the marketplace.