blog

Home / DeveloperSection / Blogs / UNSAFE CODE in C#

UNSAFE CODE in C#

Amit Singh4102 12-Feb-2011

The C# language has omitted pointers as a data type. C#instead provides references and the ability to create objects that are managedby a garbage collector. This design contributes in making C# a much saferlanguage than C or C++.These categories are main cause of bugs in C and C++programs, so are eliminated in c#.

In unsafe code it is possible to declare and operate onpointers, to perform conversions between pointers and integral types, to takethe address of variables.

Unsafe contexts

The unsafe features are available only in unsafe contexts.An unsafe context is introduced by including an unsafe modifier in thedeclaration.

·         Adeclaration of a class, struct, interface, or delegate may include an unsafemodifier, in which case the entire declaration (including the body of theclass, struct, or interface) is considered an unsafe context.

·        A declaration of a field, method, property,event, indexer, operator, constructor, destructor, or static constructor mayinclude an unsafe modifier, in which case the entire member declaration isconsidered an unsafe context.

·        An unsafe-statement enables the use of an unsafecontext within a block. The entire associated block is considered an unsafecontext.

Example:
public classSample
{
publicunsafe virtual void show() {
char* p;
//other codehere//
}
}


The unsafemodifier on the show method in sample class simply causes the show to become anunsafe context in which the unsafe features of the language can be used.


Updated 18-Sep-2014

Leave Comment

Comments

Liked By