rjmurillo / EffectiveCSharp.Analyzers

Many of the recommendations in the book Effective C#: 50 Specific Ways to Improve Your C# can be validated by Roslyn-based analyzers and code fixes.
MIT License
2 stars 1 forks source link

Item 3: Prefer the is or as Operators to Casts #27

Closed rjmurillo closed 2 months ago

rjmurillo commented 2 months ago

Related: https://github.com/BillWagner/EffectiveCSharpAnalyzers/issues/3

Use the as operator whenever you can because it is safer than casting and more efficient at runtime. The as and is operators do not perform any user-defined conversions. They only succeed if the runtime type matches the sought type and rarely construct a new object. The exception is the as operator will create a new type when converting a boxed value type to an unboxed nullable value type.