Skip to content

Attributes without parameters are never constructed when calling Type.GetCustomAttributes() #1584

Closed
nanoframework/CoreLibrary
#218
@CoryCharlton

Description

@CoryCharlton

Target name(s)

No response

Firmware version

No response

Was working before? On which version?

No response

Device capabilities

No response

Description

If an attribute has a default constructor (without parameters) it is never executed after calling Type.GetCustomAttributes(). An object of the correct type is returned but it is in an unconstructed state.

How to reproduce

https://github.com/CoryCharlton/NF.AttributeConstructorExample/blob/main/Issue_1584/Program.cs

using System;
using System.Threading;

namespace Issue_1584
{
    public class Program
    {
        public static void Main()
        {
            Console.WriteLine("[1] Program starting");

            var attributes = typeof(ExampleClass).GetCustomAttributes(true);

            Console.WriteLine($"[3] {attributes.Length} attribute retrieved.");
            Console.WriteLine($"[4] Attribute is of type {attributes[0].GetType().Name}");

            Thread.Sleep(Timeout.Infinite);
        }
    }

    public class ExampleAttribute : Attribute
    {
        public ExampleAttribute()
        {
            Console.WriteLine($"[2] {nameof(ExampleAttribute)}.ctor() is never called");
        }
    }

    [Example]
    public class ExampleClass
    {

    }
}

Expected behaviour

The constructor is called.

Screenshots

No response

Aditional information

I took at look at the code and believe the issue exists here:

https://github.com/nanoframework/nf-interpreter/blob/10dfd6198707691d555d922a71abc123a1bceebe/src/CLR/CorLib/corlib_native_System_RuntimeType.cpp#L362

Unfortunately I'm not familiar enough with this code, or the type system in general, to determine where the actual constructor is executed or what is missing.

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions