Search  Search  

Usage of Unsafe Code in C#
  More Programming ... on Twitter on YouTube on flickr on Pinterest on Facebook on Google+ on Tumblr on LinkedIn

Free wallpapers of the hottest girls of the 2014 Winter Olympics

Complete guide for Euro 2012’, about 300 hundred pages filled with comprehensive information about Euro 2012

Euro 12 - teams, managers, players, fixtures, referees, the brand new ‘Tango 12’ Adidas ball and much, much more. Few hundreds amazing photos.

E-books, free e-books, Euro 2012 e-books

Auckland events in photos at

1 500 photos of fun-run 'Ports of Auckland Round the Bays 2012' at

Ocean swim - more than 1 500 photos of State King of the Bays Forums forums Forums - articles, news, links Forums - articles, news, links 

Photos of State King of the Bays event at

‘Complete guide for Euro 2012’: Given profile all 368 footballers with their photos.

‘Complete guide for Euro 2012’: Read about star players of each squad. Find out who is the key player of each team. What Pele expects of Euro 2012?

‘Complete guide for Euro 2012’: Compare annual salary of coaches participating in the Euro-2012 - and how it happened that the team of the most paid coach finished the last in their group?

‘Complete guide for Euro 2012’: Euro 2012 footballers: who are the most expensive players? Who are the Rising stars at Euro 2012?

E-books, free e-books, Euro 2012 e-books
 Rating: 4      Rate this article   30 
 15 Jun 2011

Usage of Unsafe Code in C#


New Page 2

Any code that makes use of pointers has to be marked unsafe. This is
done using the unsafekeyword. Individual statements can be marked
unsafe, or entire methods can be marked unsafe, depending on how much
unsafe code is used.

Take a look at the following example:

using System; class UnsafeClass {

unsafe public static void Main()
{ int var1 = 7; int* var2; var2 = &var1;
Console.WriteLine( “Initial value is “ + *var2 ); *var2 = 10;
Console.WriteLine( “New value is “ + *var2); Console.ReadLine();

This code contains some interesting points worth highlighting. Here
Main()is marked as unsafe:

unsafe public static void Main()

Here a pointer is created:
int* var2; The address of var1 is placed in the pointer var2: var2 =

The initial value output is assigned:

Console.WriteLine( “Initial value is “ + *var2 );
Now the value 10is assigned to the variable via the pointer created:
*var2 = 10;

A new value is output:
Console.WriteLine( “New value is “ + *var2);

If this code were compiled and run, the output would be as follows:
Initial value is 7 New value is 10

Using the fixed Modifier

The fixedmodifier is often used when working with pointers. It is used
to prevent a managed variable from being moved by the garbage collector.
This is needed, for example, when a pointer refers to a field in a class

Since the pointer has no knowledge of the actions of the garbage
collector, if the object is moved, the pointer will point to the wrong
object. The fixedmodifier is a way to prevent this from happening.
Here is a general form of fixed:

fixed ( type* p = &var1 ) { // use fixed object }

Here, pis a pointer being assigned the address of a variable. The object
will remain at the current mem¬ory location until the block of code has
executed. Note that the fixedkeyword can be used only in an unsafe
context. You can declare more than one fixed pointer at a time using a
comma-separated list.

Here is an example of fixed in action:

using System; class Test
public int number;
public Test(int x)
number = x;

class FixedExample

unsafe public static void Main()


Test test=new Test(21);

fixed ( int* pointer1 = &test.number)
Console.WriteLine( “Initial value is “ + *pointer1);

*pointer1 = 7;

Console.WriteLine( “New value is “ + *pointer1);


In this example, fixedprevents testfrom being moved. Because the pointer
points to test.number, if testwere moved, the pointer would point to an
invalid location.

Let’s take a look at the highlights of this code.

Here we are declaring a class called Testfor use.

class Test

public int number;
public Test(int x)

number = x;

unsafe public static void Main()

Here fixedis used to put the address of test.numberinto the pointer:

fixed ( int* pointer1 = &test.number)

We now output the initial value to the screen:

Console.WriteLine( “Initial value is “ + *pointer1);

A new number is now assigned via the pointer that was created:
*pointer1 = 7;

An altered value is now displayed:

Console.WriteLine( “New value is “ + *pointer1);

The output from this program will be as follows:

Initial value is 21 New value is 7

sizeof Operator

The sizeofoperator is interesting to use. It can be used to return the
number of bytes occupied by a data type.

The following is an example of the sizeofoperator in action:


Console.WriteLine(“bool: {0}”, sizeof(bool));

Console.WriteLine(“byte: {0}”, sizeof(byte));

Console.WriteLine(“sbyte: {0}”, sizeof(sbyte));
Console.WriteLine(“short: {0}”, sizeof(short));
Console.WriteLine(“ushort: {0}”, sizeof(ushort));
Console.WriteLine(“int: {0}”, sizeof(int));

Console.WriteLine(“uint: {0}”, sizeof(uint));

Console.WriteLine(“long: {0}”, sizeof(long));
Console.WriteLine(“ulong: {0}”, sizeof(ulong));

Console.WriteLine(“char: {0}”, sizeof(char));

Console.WriteLine(“float: {0}”, sizeof(float));
Console.WriteLine(“double: {0}”, sizeof(double));
Console.WriteLine(“decimal: {0}”, sizeof(decimal));

The output from this code is as follows:
bool: 1 byte: 1 sbyte: 1 short: 2 ushort: 2 int: 4 uint: 4 long: 8
ulong: 8 char: 2 float: 4 double: 8 decimal: 16

Using stackalloc

The keyword stackallocinstructs the runtime to allocate a portion of
memory on the stack. It requires two things:
❑ The type
❑ The number of variables you’re allocating to the stack

For example, if you want to allocate enough memory to store five floats,
you can write the following:
float *pointerfloat = stackalloc float [5];

To allocate enough memory to store 21 shorts:
short *pointershort = stackalloc short [21];

It is important to remember that stackallocsimply allocates memory. It
doesn’t initialize it to any value. The advantage of stackallocis the
ultrahigh performance it offers, and it is left up to you to ini¬tialize
the memory locations that were allocated. One useful application of
stackallocis in creating arrays directly in the stack, which is far more
efficient than arrays that are objects instantiated from System.Array,
which are stored in the heap.

Compiling Unsafe Code

If you’ve tried to compile any of the preceding unsafe code, you will
have received an error like this:
error CS0227: Unsafe code may only appear if compiling with /unsafe
To compile unsafe code using the command-line compiler, you will need to
add the /unsafeargument:
csc test.cs /unsafe
This will allow the code to be compiled. To compile the code under
Visual Studio .NET, you will need to go to the project property page and
set Allow Unsafe Code Blocks to Truein Configuration properties


  More similar links:

How to test string for a number?

Pointers Basics

Hardware Requirements for Microsoft Visual Studio 2010

How to test Credit Cards validity in C#. Sample code.

Usage of Unsafe Code in C#

Unsafe Code Usage in C#

Drag and drop a file in C# - easy.

 Rate this article from 1 to 5 

        Add comment
Your name:
Your comment:
 Tags: Unsafe, Code, pointers, memory stack, Visual Studio .NET
   More Programming ...

  Home page Weird We sell Programming Windows
  News Our Photos Photoshop and Photography SQL server Microsoft Office
  Tech News Our Portfolio iPad Misc Web sites development
  Videos Archive Androids Graphic design Software development
  Auckland and New Zealand About Us Tablet PCs CD/DVD presentation Play games online
  Football Contact us Round the Bays 2012 photos Ocean Swim 2012 photos Auckland Events
  Sport Our Portfolio Stock Images Stock Photos Links Exchange
  Hot Girls Our clients On Twitter Add link Site Map
  Our Twitters’ gadget Site Map Google+ Site Grid
  Health and Beauty Site Grid Pinterest Natalia Soft Fern forums
  Misc News Web pages Facebook Photos, images Hair & Beauty
  On YouTube CD/DVD presentaton Tumblr Daily Motion Flickr
  YouTube - 2 Graphics LinkedIn Live Journal Stumble Upon
  Vimeo - videos Tutorials - Videos Tutorials - Weird Most Popular on Internet Yahts, boats, Tall Ships

SoftFern (New Zealand LTD). 
Design and development by SoftFern 2003 - 2014 Graphics supplied by