none
Static class methods overloads use cause a compiler error RRS feed

  • Question

  • I have a problem using static class method overloads (not sure if it reproduces on non-static classes)

    I have 3 projects. The are in ref chan like project-1 references project-2, project-3 references project-2. That means project-3 dont have direct project-1 reference.

    On the project-2 i have a static class that contains method with two overloads: one have a parameter of string, and one - the type from project-1. When im trying to call method from project-3 using overload with string param, the compiler raise an error that i must reference project-1 in project 3. If i create a new method and do the same as overloaded method with string param - everythig works fine. I'll try to explain in code.

    Project-1

    public class Foo
    {
       public string Text { get; set; }
       public string Bar()
       {
          return Text + " bar";
       }
    }

    Project-2 (references Project-1)

    public static class StaticClass
    {
       public static string RunAnother(string str)
       {
          var foo = new Foo { Text = str };
          return Run(foo);
       }
    
       public static string Run (string str)
       {
          var foo = new Foo { Text = str };
          return Run(foo);
       }
    
       public static string Run(Foo foo)
       {
          return foo.Bar();
       }
    }

    Project-3 (References ONLY project-2)

    var t1 = StaticClass.Run("test"); //Compile error: " The type 'Foo' is defined in an assembly that is not referenced."
    
    var t2 = StaticClass.RunAnother("test"); //Works great

    Why is it so?


    Tuesday, January 29, 2019 10:03 AM

All replies

  • To compile your code the compile must have access to the metadata associated with each type used. If it cannot find it then it generates a compiler error. The type would include any base types as well since the compiler has to determine information about the type such as whether it is value or reference and what base members are available. Hence if you use a method that requires type A from project 1 then you have to include a reference to it as well. Ultimately the fact that you're referencing a method from project 2 is irrelevant here as you're going to need a type (either to pass or as the return value) from project 1 so project 1 is a required reference.

    Now, why are you getting it on the Run call but not RunAnother? That is because of overloading. Because there are multiple overloads for Run the compiler has to look at all the overloads and narrow down which one to call based upon your arguments. To do that it needs the metadata for the types, hence the error. 


    Michael Taylor http://www.michaeltaylorp3.net

    Tuesday, January 29, 2019 2:55 PM
    Moderator