Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the compiler fail to find the right type?

I have a method and a class with the same name. In a case, the compiler understands that I am using the class name, but not in another case:

using System;
using DTO;

namespace DTO
{
    public class Foo
    {
        public string Bar { get; set; }
    }
}

namespace Tests
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
        }

        private void Foo()
        {
            var foo = new Foo // Ok
            {
                Bar = nameof(Foo.Bar) // Not ok
            };
        }
    }
}

Error:

CS0119 'Program.Foo()' is a method, which is not valid in the given context

I get the same error with a static property:

public class Foo
{
    public static string Bar = "Hello";
}

// ...

private void Foo()
{
    var bar = Foo.Bar; // Error
}

If the compiler understands in the context that the Foo in new Foo is a class, why cannot it understand that Foo in nameof(Foo.Bar) is also a class? This notation makes no sense if Foo is a method.

like image 256
Boiethios Avatar asked Nov 23 '25 05:11

Boiethios


1 Answers

In the first case the compiler knows you mean the class because of the new keyword. What follows new has to be a type name.

In the second case, there is no such restriction: Foo can be any variable, member, field or type. (Note that if this should work at all, Bar needs to be a static property of class Foo).

But since the method Foo is in the closest scope, the compiler thinks you mean this method group, which has no member called Bar.

like image 91
René Vogt Avatar answered Nov 25 '25 18:11

René Vogt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!