Muokkaa

Jaa


CA2263: Prefer generic overload when type is known

Value
Rule ID CA2263
Title Prefer generic overload when type is known
Category Usage
Fix is breaking or non-breaking Non-breaking
Enabled by default in .NET 9 As suggestion

Cause

A method overload that accepts a System.Type argument is called when the type is known at compile time and a suitable generic overload is available.

Rule description

Generic overloads are preferable to overloads that accept an argument of type System.Type when the type is known at compile time (using the typeof operator in C# or the GetType operator in Visual Basic). Generic overloads promote cleaner and more type-safe code with improved compile-time checks.

How to fix violations

To fix a violation of this rule, use the suitable generic overload.

Example

The following code snippet shows a violation of CA2263:

int size = Marshal.SizeOf(typeof(bool));
Dim size As Integer = Marshal.SizeOf(GetType(Boolean))

The following code snippet fixes the violation:

int size = Marshal.SizeOf<bool>();
Dim size As Integer = Marshal.SizeOf(Of Boolean)()

When to suppress warnings

It is safe to suppress a warning from this rule; however, we recommend that you use a generic overload if possible.

Suppress a warning

If you just want to suppress a single violation, add preprocessor directives to your source file to disable and then re-enable the rule.

#pragma warning disable CA2263
// The code that's violating the rule is on this line.
#pragma warning restore CA2263

To disable the rule for a file, folder, or project, set its severity to none in the configuration file.

[*.{cs,vb}]
dotnet_diagnostic.CA2263.severity = none

For more information, see How to suppress code analysis warnings.