4

It would be great if this would work. Am I trying to implement my idea in the wrong way?

I would like to use partial method, to be able to extend existing code, and simply plug in/out implementation of methods.

Basically exactly what the reference is stating:

Partial methods enable class designers to provide method hooks, similar to event handlers, that developers may decide to implement or not. If the developer does not supply an implementation, the compiler removes the signature at compile time.

My first try of using this is the following:

DefinitionsBase.cs:

namespace ABC {
    public partial class Definitions {
        // No implementation
        static partial void TestImplementaion();
    }
}

DefinitionsExt.cs:

namespace ABC {
    public partial class Definitions {
        static partial void TestImplementaion(){
            // Implementation is here
        }
    }
}

Program.cs:

namespace ABC {
    class Program {
        static void Main(string[] args) {
            Definitions.TestImplementaion();
        }
    }
}

It's same namespace, but as reference states partial methods are implicitly private. It doesn't accept access modifiers and I cannot call it from my class. Is there a way to use it as I intend to?

Thanks!

DDan
  • 8,068
  • 5
  • 33
  • 52
  • Why are you doing this? Are you using some custom code generator? – Luaan Sep 22 '15 at 07:56
  • Yes, I generate different implementations based on requirements, and I want to be able to simply plug in/out the changes by keeping the common base code intact. – DDan Sep 22 '15 at 07:59
  • Are you sure static partial methods are the best way to do this? Why not just use abstract classes or interfaces, for example? – Luaan Sep 22 '15 at 08:07
  • You are right @Luaan. Definitely better to use abstract classes and interfaces, and overriding methods to have separate implementations. I am doing that. This is more like a patch-like fixes and quick solutions by just dropping in the extension file, and not changing any of the existing code, you get an alternate method implementation. – DDan Sep 22 '15 at 09:18

1 Answers1

3

You could use a public method that calls the private method, but I am not sure if this is what you want. This just makes your code work.

Partial methods are by definition private so as during compilation time, in case the method was not implemented, the compiler does not need to go through all of the code, find all possible references to the method, and remove them. This is a design choice since partial methods do not necessarily need to be implemented, the compiler only looks in the partial class implementation and not throughout all of the code. If you implement a public method that calls the partial method and the partial method was not implemented, the compiler will still only look in the partial class files and code, even though you have access to that partial method from anywhere in your code.

John Demetriou
  • 4,093
  • 6
  • 52
  • 88