What is the need for unsafe code in C#?

If you were using C, C++ languages before developing applications using C#, then you would have extensively used pointers. Hence while using C#, you might find it difficult to get rid of pointers completely and of course there might be situations which require direct accessing of memory.



In such justifiable scenarios, C# allows you to use pointers but with a restriction that the code using pointers should be wrapped inside an unsafe code block. Not just a code block, an entire method or even a single line of code can be marked as unsafe. Here is an example demonstrating usage of unsafe code block:

public class sampleClass {
public static void Main() {
unsafe {
int sampleInt = 500;
int* ptr_sampleInt = &sampleInt;
Console.WriteLine(“sampleInt = “ + sampleInt);
Console.WriteLine(“Address of sampleInt = ” + (int)ptr_sampleInt);
* ptr_sampleInt -= 10;
Console.WriteLine(“sampleInt = “ + ptr_sampleInt->ToString());
}
}
}

In this code, you use a pointer to point to address of an integer. When you execute this code, you will end up in the following error:

“Unsafe code may only appear if compiling with /unsafe”

This is because using unsafe code might be harmful because memory is directly accessed. Hence while compiling the User should be aware that unsafe code is present in the program. For that, User is asked to explicitly compile such program with /unsafe option as shown below:
csc /unsafe sampleClass.cs

| What is the need for Bridge Pattern in C#? | What is the need for Builder Pattern in C#? | What is the need for Chain of Responsibility Pattern in C#? | What is the need for Command Pattern in C#? | What is the need for Composite Pattern in C#? | What is the need for Decorator Pattern in C#? | What is the need for Flyweight Pattern in C#? | What is the need for Interpreter Pattern in C#? | What is the need for Iterator Pattern in C#? | What is the need for Mediator Pattern in C#? | What is the need for Memento Pattern in C#? | What is the need for Prototype Pattern in C#? | What is the need for State Pattern in C#? | What is the need for Strategy Pattern in C#? | What is the need for Template Method Pattern in C#? | What is the need for unsafe code in C#? | What is the purpose of assert() in C#? | What is the purpose of AutoResetEvent in .NET? | What is the purpose of Console.ReadLine() in C#? | What is the purpose of machine.config file in .NET? |


“Amazon and the Amazon logo are trademarks of Amazon.com, Inc. or its affiliates.”

| Privacy Policy for www.dotnet-guide.com | Disclosure | Contact |

Copyright - © 2004 - 2024 - All Rights Reserved.