Câu hỏi phỏng vấn .NET Core
Câu hỏi

Explain the difference between Managed and Unmanaged code in .NET?

Câu trả lời

In .NET, the distinction between managed and unmanaged code is fundamental and revolves around how the code is executed and managed by the runtime environment.

Managed Code

Managed code is executed by the Common Language Runtime (CLR), which is a core component of the .NET framework. When you write code in high-level languages such as C#, VB.NET, or F#, it is compiled into an Intermediate Language (IL), also known as Common Intermediate Language (CIL) or Microsoft Intermediate Language (MSIL). This IL code is then executed by the CLR, which provides several essential services:

  • Memory Management: The CLR handles memory allocation and deallocation automatically through garbage collection, which helps prevent memory leaks and buffer overflows.
  • Security: Managed code benefits from built-in security features provided by the CLR, such as code access security and type safety.
  • Exception Handling: The CLR provides a robust exception handling mechanism.
  • Platform Independence: Managed code is compiled into IL, which is platform-independent. The CLR's Just-In-Time (JIT) compiler converts IL into native machine code specific to the underlying architecture at runtime.

Unmanaged Code

Unmanaged code, on the other hand, is executed directly by the operating system. This type of code is typically written in languages like C or C++ and is compiled directly into native machine code. Key characteristics of unmanaged code include:

  • Direct Execution: Unmanaged code is executed directly by the CPU without the intervention of a runtime environment like the CLR.
  • Manual Memory Management: Developers are responsible for managing memory allocation and deallocation, which can lead to issues such as memory leaks and buffer overflows if not handled correctly.
  • Security: Unmanaged code does not benefit from the security features provided by the CLR. Developers must implement their own security measures.
  • Performance: Unmanaged code can offer better performance in certain scenarios because it runs directly on the hardware without the overhead of a runtime environment.

Key Differences

Feature Managed Code Unmanaged Code
Execution By CLR Directly by the OS
Memory Management Automatic (Garbage Collection) Manual
Security Built-in by CLR Developer's responsibility
Compilation Compile...
middle

middle

Gợi ý câu hỏi phỏng vấn

senior

How to choose the target version of .NET Standard library?

middle

What is the correct pattern to implement long running background work in Asp.Net Core?

senior

Why does .NET Standard library exist?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào