Skip to content

CallerMemberName should work on target typed new() #49547

@HobbsCode

Description

@HobbsCode

Description

CallerMemberNameAttribute is not working correctly with the new target typing feature.
The caller should be the same regardless of target typing. However, the attribute is currently not being respected when target typing new(). The program below demonstrates.

using System;
using System.Runtime.CompilerServices;

namespace ConsoleApp2
{
    class Foo
    {
        public string Caller { get; set; }
        public Foo([CallerMemberName] string caller = "?") => Caller = caller;
        public void PrintCaller() => Console.WriteLine(Caller);
    }

    class Program
    {
        static void Main()
        {            
            Foo f1 = new Foo(); // Explicit typing
            f1.PrintCaller();   // Prints "Main"
            
            Foo f2 = new();   // Target typing
            f2.PrintCaller(); // Prints "?"

            Console.WriteLine("\n\nPress any key...");
            _ = Console.ReadKey(intercept: true);
        }
    }
}

Configuration

.NET 5.0.100 (C# 9)
Win10-1909 x64

Regression?

No. New feature in C# 9.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Area-CompilersuntriagedIssues and PRs which have not yet been triaged by a lead

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions