Code generation issue, override existing method implementation

Is there a way to override an existing method in a partial class?

Something like this (I know this doesn't compile)

/// <summary>
/// Generated Code for MyClass
/// </summary>
public partial class MyClass
{
    public void MyMethod()
    {
        //Do work specific to MyClass
    }
}

/// <summary>
/// Non-generated extension for MyClass
/// </summary>
public partial class MyClass
{
    public override void MyMethod()
    {
        //Do some other work
    }
}

I am running into this need while doing some code generation. I am generating partial classes from my EDMX and methods for these classes where 90% of my classes will have methods specific to their properties.

But I am running into cases where I would like the one-off the methods.

Is there something like this I am overlooking? Or some suggested alternatives?

Answers


You can use a partial method for this. I assume you can extrapolate here if you need to make changes to the signature, etc.

It's also worth noting that if you define a partial method and nobody defines an implementation for it in another partial bit of the class it just turns into a no-op, not an error, so you don't need to worry about that causing problems. It was literally built for just this use case.

/// <summary>
/// Generated Code for MyClass
/// </summary>
public partial class MyClass
{
    private partial void MyMethodImpl();
    public void MyMethod()
    {
        //Do work specific to MyClass

        MyMethodImpl();
    }
}

/// <summary>
/// Non-generated extension for MyClass
/// </summary>
public partial class MyClass
{
    public void MyMethodImpl()
    {
        //Do some other work
    }
}

We use the double-derived pattern with flagged extension points extensively in our codebase. http://msdn.microsoft.com/en-us/library/bb126289(v=vs.100).aspx

Generated code looks like this:

public abstract class FooBase
{
   protected FooBase()
   {
   }
   public virtual int GetSomeThing()
   {
      // ... some generated implementation ...
   }
}

public partial class Foo
{
   public Foo() : FooBase()
   {
   }
   // Nothing except the constructor generated in this class.
}

We then will occasionally have generated methods flag their need for manual code by generating methods that don't compile, with a large comment providing a stub implementation for the manual code that's required. It's been pretty successful.


Why not derive from the generated class and override methods in the derived class?


Need Your Help

Changing row color on click - ASP.NET and JavaScript

javascript html asp.net gridview background-color

Using the e.Row.Attributes.Add("onclick", "this.style.backgroundColor='yellow'"); I am able to highlight a selection with a mouseclick in an ASP.NET GridView.