Unmanaged code¶
ID: cs/unmanaged-codeKind: problemSecurity severity: Severity: recommendationPrecision: highTags: - quality - reliability - correctnessQuery suites: - csharp-security-and-quality.qls
Click to see the query in the CodeQL repository
Microsoft defines two broad categories for source code. Managed code compiles into bytecode and is then executed by a virtual machine. Unmanaged code is compiled directly into machine code. All C# code is managed but it is possible to call external unmanaged code. This rule findsextern methods that are implemented by unmanaged code. Managed code has many advantages over unmanaged code such as built in memory management performed by the virtual machine and the ability to run compiled programs on a wider variety of architectures.
Recommendation¶
Consider whether the unmanagedextern methods could be implemented in C# instead.
Example¶
This example shows a function that displays a message box when clicked. The unmanaged code is shown first and then the same function being performed by managed code is shown after.
// example of using unmanaged codeusingSystem;usingSystem.Windows.Forms;usingSystem.Runtime.InteropServices;publicpartialclassUnmanagedCodeExample:Form{[DllImport("User32.dll")]publicstaticexternintMessageBox(inth,stringm,stringc,inttype);// BADprivatevoidbtnSayHello_Click(objectsender,EventArgse){MessageBox(0,"Hello World","Title",0);}}// the same thing in managed codeusingSystem;usingSystem.Windows.Forms;publicpartialclassManagedCodeExample:Form{privatevoidbtnSayHello_Click(objectsender,EventArgse){MessageBox.Show("Hello World","Title");}}
References¶
MSDN, C# Referenceextern.
Wikipedia,Managed code.