Skip to content

ArgumentNullException when retrieving the default value of an Enum property defined with an integer #41498

Closed

Description

@icom85

It is related to the DefaultValueAttribute, the Enums and the PropertyDescriptor class. The issue is in the static Enum.ToObject method. In order to observe the issue, it is necessary to use an integer as a default value of an enumeration. The code below easily reproduces it:

using System.ComponentModel;
using System.Windows.Forms;

namespace EnumDefaultValueIssue
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            var btn = new MyButton();
            var properties = TypeDescriptor.GetProperties(btn);
            var prop = properties["Dock"];

            // Crashes when calling ShouldSerializeValue on the PropertyDescriptor
            var shouldSerialize = prop.ShouldSerializeValue(btn);
        }
    }

    public class MyButton
    {
        //[DefaultValueAttribute(DockStyle.None)] //No crash
        [DefaultValueAttribute(0)] // Crash
        public DockStyle Dock { get;  set; }
    }
}

I`ve tested with the latest .NET 5.0 - 5.0.100-preview.8.20417.9, the issue is likely to be observed with other .NET Core runtimes. The same setup is working well in the full .NET framework.

Workaround:
Don't use the underlying integer type in the DefaultValueAttribute but rather the real enum member.

Activity

  1. Dotnet-GitSync-Bot commented on Aug 28, 2020

    @Dotnet-GitSync-Bot
    Collaborator

    I couldn't figure out the best area label to add to this issue. If you have write-permissions please help me learn by adding exactly one area label.

  2. joperezr commented on Aug 28, 2020

    @joperezr
    Member

    Moving to ComponentModel given the issue seems to be with the way that ReflectPropertyDescriptor is trying to get the default value of the object. This is not a regression, as I can at least repro with 3.1

  3. removed
    untriagedNew issue has not been triaged by the area owner
    on Aug 28, 2020
  4. added this to the 6.0.0 milestone on Aug 28, 2020
  5. safern commented on Aug 28, 2020

    @safern
    Member

    Marking as 6.0.0 since it is not a regression. However I might be able to fix this while nullable annotating TypeConverters.

  6. self-assigned this
    on Aug 28, 2020
  7. safern commented on Aug 10, 2021

    @safern
    Member

    This was fixed in: #55793

  8. ghost locked as resolved and limited conversation to collaborators on Sep 9, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions