Home > Microsoft .Net Development Tips > Application Testing and Security > Writing unsafe code in C#
Win Development Tips:
EMAIL THIS
 TIPS & NEWSLETTERS TOPICS 

APPLICATION TESTING AND SECURITY

Writing unsafe code in C#


Kunal Cheda
03.15.2003
Rating: --- (out of 5)


Digg This!    StumbleUpon Toolbar StumbleUpon    Bookmark with Delicious Del.icio.us   


Let other users know how useful this tip is by rating it below. Got a tip or code of your own you'd like to share? Submit it here!


C# statements execute in either a safe or an unsafe context. Safe context is the default, but any code using pointers requires unsafe context.The unsafe keyword denotes an unsafe context. Again, unsafe context is required for any operation involving pointers.

Unsafe code, or a block of code which is marked as unsafe, is managed by CLR, but a programmer is allowed to use pointers to manipulate memory directly. This code runs outside the control of memory management (GC). When you compile this code, it is unable to escape the watchful eye of the CLR. Unsafe can be applied as a modifier in the declaration of callable members such as methods, properties, constructors and extenders (but not static constructors).

Using unsafe code is more efficient than using references to access objects, imparts an extra layer and GC adds its overheads. You may use unsafe code to parts of your application where you want to be as efficient as possible. You may want to use COM interface method, which requires a pointer as an argument. You may also want to some C or C++ code that uses pointer if you don't want to convert the pointers to references.

Pointer is a variable that holds an address of a variable. Pointer variables have to be typed so that int* declares a 'pointer to int' and can only be used to hold the address of an int. Pointer variables can only be declared and used within unsafe blocks, because the GC has to be informed about using the pointer variables in your code.

using System;
class UnsafeTest
{
public static void Main()
{ int i = 5,k= 10;
unsafe
{ 
int j = Add(&i,&k); // &i means address of i variable  
Console.WriteLine(j);
}
}
unsafe static int Add(int* p,int* q) //declare pointer variable int* p
{ 
return (*p + *q); // *p gets the value stored at location p 
}
} 

Save the above code as UnsafeTest.cs.

Compile    c:\>csc UnasfeTest.cs 
run          c:\>UnsafeTest 


Source: DotNetExtreme.com

Rate this Tip
To rate tips, you must be a member of SearchWinDevelopment.com.
Register now to start rating these tips. Log in if you are already a member.




Digg This!    StumbleUpon Toolbar StumbleUpon    Bookmark with Delicious Del.icio.us   



RELATED CONTENT
C# Development
Let Microsoft StyleCop tame your wild C#
Picking a .NET smart client communications technology
LINQ beyond queries: Strong-typed refection
Book excerpt: An introduction to DSL tools
Assembly versioning in the .NET Framework 2.0
Book excerpt: Creating graphical output using the .NET Compact Framework
On Extension Methods in C# and .NET Framework 3.5
Generate RSA public and private keys, export to XML
Book excerpt: Upgrading to Visual Studio 2005
Learning .NET: Tips for getting started with .NET development

Application Testing and Security
Test-driven development in .NET yields complete unit test coverage
How to write installers in Vista that work correctly under UAC
How to elevate programs' privileges correctly using Vista's UAC
Internet Explorer 8 beta's development tools add source visualizations
Microsoft previews new features in Visual Studio 2010
Advanced Windows Debugging Book Chapter and Podcast
Book excerpt: Advanced Windows Debugging
Book excerpt: Pragmatic unit testing in C# with NUnit
Security interoperability with .NET/WSE and WebLogic Workshop 8.1
How to avoid regression bugs while adding new features

.NET Framework security best practices
New features in Windows 7 bring new UI considerations for developers
Podcast: Windows CardSpace authors speak
Book excerpt: Java EE and .NET security interoperability
Book excerpt: Advanced Windows Debugging
Book excerpt: Pragmatic unit testing in C# with NUnit
Security interoperability with .NET/WSE and WebLogic Workshop 8.1
Windows Developments: Product news, December 2007
How to avoid regression bugs while adding new features
VB code: New additions, November 2007
VB code: Application security downloads

RELATED GLOSSARY TERMS
Terms from Whatis.com − the technology online dictionary
common test platform  (SearchWinDevelopment.com)

RELATED RESOURCES
2020software.com, trial software downloads for accounting software, ERP software, CRM software and business software systems
Search Bitpipe.com for the latest white papers and business webcasts
Whatis.com, the online computer dictionary

DISCLAIMER: Our Tips Exchange is a forum for you to share technical advice and expertise with your peers and to learn from other enterprise IT professionals. TechTarget provides the infrastructure to facilitate this sharing of information. However, we cannot guarantee the accuracy or validity of the material submitted. You agree that your use of the Ask The Expert services and your reliance on any questions, answers, information or other materials received through this Web site is at your own risk.



Database Programming Solutions - .NET XML, Visual Studio LINQ, ORM .NET
About Us  |  Contact Us  |  For Advertisers  |  For Business Partners  |  Site Index  |  RSS
SEARCH 
TechTarget provides technology professionals with the information they need to perform their jobs - from developing strategy, to making cost-effective purchase decisions and managing their organizations' technology projects - with its network of technology-specific websites, events and online magazines.

TechTarget Corporate Web Site  |  Media Kits  |  Site Map




All Rights Reserved, Copyright 2000 - 2009, TechTarget | Read our Privacy Policy
  TechTarget - The IT Media ROI Experts