What is managed code and unmanaged code in c# with example
Managed code and unmanaged code are terms used in the context of C# and the .NET framework to describe how the code is executed and managed by the runtime environment. Here's an explanation and an example of each:
1. Managed Code:
- Managed code refers to code that is executed within the .NET Common Language Runtime (CLR) environment. The CLR provides various services such as memory management, type safety, and garbage collection.
- C# code is typically considered managed code because it is compiled into an intermediate language (IL) that is executed by the CLR.
Example of managed code in C#:
```csharp
using System;
class Program
{
static void Main()
{
Console.WriteLine("This is managed code executed by the CLR.");
}
}
```
2. Unmanaged Code:
- Unmanaged code is code that is executed outside the control and management of the CLR. It does not rely on the services provided by the .NET framework, and it may directly interact with the system or other libraries.
Example of unmanaged code in C# (using Platform Invocation Services - P/Invoke to call unmanaged code in a DLL):
```csharp
using System;
using System.Runtime.InteropServices;
class Program
{
[DllImport("kernel32.dll")]
static extern int MessageBox(IntPtr hWnd, string text, string caption, int options);
static void Main()
{
MessageBox(IntPtr.Zero, "This is unmanaged code called from managed code.", "Message", 0);
}
}
```
In the unmanaged code example, we use the `[DllImport]` attribute to call a function from the Windows Kernel32 library, which is unmanaged code. This demonstrates how managed C# code can interact with unmanaged code through Platform Invocation Services (P/Invoke). Unmanaged code is typically used when working with low-level system functions or third-party libraries that are not managed by the CLR.
Comments
Post a Comment