- 필수 기능
- 시작하기
- Glossary
- 표준 속성
- Guides
- Agent
- 통합
- 개방형텔레메트리
- 개발자
- Administrator's Guide
- API
- Datadog Mobile App
- CoScreen
- Cloudcraft
- 앱 내
- 서비스 관리
- 인프라스트럭처
- 애플리케이션 성능
- APM
- Continuous Profiler
- 스팬 시각화
- 데이터 스트림 모니터링
- 데이터 작업 모니터링
- 디지털 경험
- 소프트웨어 제공
- 보안
- AI Observability
- 로그 관리
- 관리
",t};e.buildCustomizationMenuUi=t;function n(e){let t='
",t}function s(e){let n=e.filter.currentValue||e.filter.defaultValue,t='${e.filter.label}
`,e.filter.options.forEach(s=>{let o=s.id===n;t+=``}),t+="${e.filter.label}
`,t+=`ID: csharp-best-practices/outattr-on-pinvoke
Language: C#
Severity: Warning
Category: Best Practices
The OutAttribute
on string parameters for P/Invoke methods is not recommended because strings in .NET are immutable. When you pass a string to a method as an output parameter, it’s not possible to modify the original string. This can lead to unexpected behaviors and bugs in your code.
This rule is important because it helps to prevent these issues, ensuring that your P/Invoke methods work correctly and as expected. Adhering to this rule will result in more robust and maintainable code.
Use StringBuilder
instead of string
for output parameters. The StringBuilder
class is mutable and can handle the modifications made by the P/Invoke method. In the compliant code example, StringBuilder
is used with the GetComputerName
method, and the method is able to modify the StringBuilder
object and reflect the changes in the calling code.
using System;
using System.Runtime.InteropServices;
class Program
{
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
public static extern void GetComputerName([Out] string name, ref int size);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
public static void GetComputerNameInternal([Out] string name, ref int size){
}
static void Main()
{
int size = 256;
string name = new string('\0', size);
GetComputerName(name, ref size);
Console.WriteLine(name);
}
}
using System;
using System.Runtime.InteropServices;
using System.Text;
class Program
{
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
public static extern bool GetComputerName(StringBuilder name, ref int size);
static void Main()
{
int size = 256;
StringBuilder name = new StringBuilder(size);
if (GetComputerName(name, ref size))
{
Console.WriteLine(name.ToString());
}
else
{
Console.WriteLine("Failed to get computer name.");
}
}
}