dotnet / dotnet/runtime

[Analyzer Proposal]: Warn when DefaultValueAttribute is used with wrong type

Open
#131,868 1 comment 0 reactions 0 assignees View on GitHub
api-suggestion area-System.ComponentModel code-analyzer
Dominant language
C#
Stars
18.3k
Forks
5.6k
PR merge metrics
PR metrics pending

Description

### Background and motivation

`DefaultValueAttribute` is non-generic by nature. There is no compile-time safety that guards against the case where the given default value doesn't match the same type as the element the attribute is applied to (that element could be property or parameter).

### API Proposal

The following sample should have a warning:

```csharp
using System.ComponentModel;

public class C
{
[DefaultValue(5)]
public uint MyProperty { get; set; } = 5;
}
```

The above calls the constructor that accepts int. This can cause issues for consumers that expect the value to be of the same type as the property. See https://github.com/dotnet/aspnetcore/issues/65050 for example.

The analyzer should suggest using `5u` or `(uint)5` in the case above.

Contributor guide

Open the contributing guide

Research direction

Start by locating the analyzer infrastructure that inspects DefaultValueAttribute usages and review how attribute argument types are compared with property or parameter types. Reproduce the uint example, then verify that a diagnostic recommends 5u or (uint)5 and does not report matching types.

Written by the indexing model from the issue text.

Assessment

Tech stack
csharp
Domain
tooling
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
52/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.