- 필수 기능
- 시작하기
- 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/is-instead-of-as
Language: C#
Severity: Notice
Category: Best Practices
The is
keyword in C# is used for checking the compatibility of an object with a given type, and the result of the operation is a Boolean: true if the object is of the given type, and false otherwise. The as
operator, on the other hand, performs a type conversion and returns the object if the conversion is successful, or null if it isn’t.
Using the as
operator to check for type compatibility can lead to less straightforward and potentially confusing code. It can also have performance implications. When you use as
, the runtime performs the type check and the conversion, and if you then use the result in a conditional statement, you’re effectively checking the type twice: once with as
, and once with the null
check.
To remediate this error, prefer using the is
keyword when the aim is to check for type compatibility. This not only makes the code clearer and more straightforward, but it also eliminates the unnecessary type check, leading to potentially better performance. For instance, instead of if (x as string != null)
, you should use if (x is string)
.
// checking type with the "as" keyword
if (x as string != null)
{
}
// testing type with is
if (foo is string)
{
}