runtime icon indicating copy to clipboard operation
runtime copied to clipboard

PropertyDescriptor's IsReadOnly returns false for a property with private set accessor

Open ighristov opened this issue 8 years ago • 3 comments

When a class has a property with a private set accessor, its PropertyDescriptor's IsReadOnly property returns false. The same code evaluates IsReadOnly to true in .NET Framework 4.7.2. The following code demonstrates the issue:

        static void AssertReadOnlyAttribute()
        {
            var foo = new Foo();
            var barProperty = TypeDescriptor.GetProperties(foo).Find("Bar", true);
            System.Diagnostics.Debug.Assert(barProperty.IsReadOnly);
        }

        class Foo
        {
            public bool Bar { get; private set; }
        }

ighristov avatar Nov 20 '18 16:11 ighristov

Hi! Any update on this issue? Will it be fixed in .Net Core 3?

pavelovcharov avatar Mar 07 '19 15:03 pavelovcharov

cc @maryamariyan @safern

jkotas avatar Mar 07 '19 16:03 jkotas

Found the issue. The difference in between Desktop and .NET Core is that when we're getting the SetMethod in ReflectTypeDescriptionProvider we use to call PropertyInfo.GetSetMethod() which would get only public set methods, when porting the code over from desktop, there was a cleanup made, that instead of calling PropertyInfo.GetSetMethod() we changed it to call PropertyInfo.GetMethod property, which gets private methods as well.

So then in .NET Core we're finding a set method for this property even though it is private, therefore, we return false on IsReadOnly because we do: return SetMethodValue == null || ((ReadOnlyAttribute)Attributes[typeof(ReadOnlyAttribute)]).IsReadOnly; since we resolve SetMethodValue correctly it is not null, and this is not marked with ReadOnlyAttribute so we return false.

Here is the change that broke this. https://github.com/dotnet/corefx/commit/2f842d37073285cf8cbc284c9317d33c5ccd4bd0#diff-e1dbd34f0de10fc23633e32bc9b3b438R1267

I'll submit a PR to fix it shortly.

safern avatar Mar 07 '19 22:03 safern