Shahid Riaz Bhatti

if(my.work == “Interesting” || my.availableTime > my.workHours) { this.blog.Post();}

How to use unsafe code in C#

September 22
by Shahid Riaz Bhatti 22. September 2008 15:44

It is a very small and basic article showing that how can we use pointers in C#. I am posting this article because most of the people think that C# does not allow the use of pointers. In this example I will create a small function which will changes the value of a variable using the Pointers. So lets start:

First of all make a simple console application. Copy the following function:  

unsafe private static void UseUnsafeCode()

{

int count = 10;

int* p;

p = &count;

System.Console.WriteLine("Value of count before changing=" + count.ToString());

*p = 25;

System.Console.WriteLine("Value of count after changing=" + count.ToString());

System.Console.ReadLine();

}

Now call the above function in the main program.

Please make sure to allow the compilation of safe code in the property of the project.

The sample code will look something like this:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace ConsoleApplication1

{

class Program

{

public static void Main(string[] args)

{

UseUnsafeCode();

}

unsafe private static void UseUnsafeCode()

{

int count = 10;int* p;

p = &count;

System.
Console.WriteLine("Value of count before changing=" + count.ToString());

*p = 25;

System.Console.WriteLine("Value of count after changing=" + count.ToString());System.

Console.ReadLine();

}

}

}

In the above example I have made a function in which I have declared two variables. The first one is count and its data type is int and the second is an int pointer. Also in the code I have changed the value of count variable using the pointer p variable. The output is given below:

Value of count before changing = 10

Value of count after chaning = 25

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: ,

C# | General | Random Thoughts | Tips and Tricks | Visual Studio

Comments

Add comment


(Will show your Gravatar icon)  

Enter the word
9116


biuquote
  • Comment
  • Preview
Loading



RecentComments

Comment RSS

Most comments

supplynflshop supplynflshop
51 comments
tiffany-bracelets tiffany-bracelets
39 comments
AVI to iPad AVI to iPad
36 comments