Skip to content

Work out how "nameof" interacts with "this" #931

@jskeet

Description

@jskeet

Originally reported on #926.

Some comments from @KalleOlaviNiemitalo

A surprising interaction with nameof:

struct S {
    int i;
    
    void M() {
        string N() {
            return nameof(this);  // error CS1673
        }

        string O() {
            return nameof(this.i);  // error CS1673
        }

        string P() {
            return nameof(i);  // OK, returns "i"
        }
    }
}

To be checked:

  • nameof(this) in a default parameter or in an attribute argument (thus not in the function body) in a local or anonymous function in a struct
using System;
class DAttribute : Attribute {
    public DAttribute(string s) {}
}
struct S {
    int j;
    void LeA() {
        // OK
        Action<int> a = ([D(nameof(this.j))] int i) => {};
    }
    void LeD() {
        // error CS1065, default value not allowed
        Action<string> action = (string s = nameof(this.j)) => {};
    }
    void LfA() {
        // OK
        void F([D(nameof(this.j))] int i) {}
    }
    void LfD() {
        // error CS1673, cannot access this in local function
        void F(string s = nameof(this.j)) {}
    }
}

That seems pretty inconsistent. Why is nameof(this.j) allowed in an attribute argument in the parameter list, but not in a default parameter value? Is that what the standard should specify?

Expression trees seem to allow neither attributes nor default values, so the behaviour is more consistent for them:

using System;
using System.Linq.Expressions;
class DAttribute : Attribute {
    public DAttribute(string s) {}
}
struct S {
    int j;
    void ExA() {
        // error CS8972, attribute not allowed in expression tree
        Expression<Func<string, string>> e = ([D(nameof(this.j))] string s) => "";
    }
    void ExD() {
        // error CS1065, default value not allowed in expression tree
        Expression<Func<string, string>> e = (string s = nameof(this.j)) => "";
    }
    void ExR() {
        // error CS1673, lambda expression in struct cannot access this
        Expression<Func<string, string>> e = (string s) => nameof(this.j);
    }
}

Metadata

Metadata

Assignees

Labels

type: bugThe Standard does not describe the language as intended or implemented

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions