Override a virtual method in a partial class

DevDave picture DevDave · Jun 21, 2013 · Viewed 16.9k times · Source

I am currently working with the nopCommerce source code and trying my best to avoid editing the source at all, but instead using partial classes and plugins that are separate from the source code, should we ever need to upgrade versions.

I want to make some changes to the code that places an order, by using a partial class in the same assembly:

Orignal Source Code:

namespace Nop.Services.Orders {

  public partial class OrderProcessingService : IOrderProcessingService {

        public virtual PlaceOrderResult PlaceOrder(ProcessPaymentRequest processPaymentRequest)
        { //....

My partial class:

namespace Nop.Services.Orders {

  public partial class OrderProcessingService : IOrderProcessingService {

    public override PlaceOrderResult PlaceOrder(ProcessPaymentRequest processPaymentRequest) { //....

When I try to compile this code I get an error:

Type 'Nop.Services.Orders.OrderProcessingService' already defines a member called 'PlaceOrder' with the same parameter types

But I am using override and the method in the original class is virtual, could someone tell me where I am going wrong here, and how I could override this method?

Answer

Claudio Redi picture Claudio Redi · Jun 21, 2013

You cannot override a virtual method on the same class. Partial classes are just the same class with definition splitted on different places, it doesn't define a hierarchy so that's just not possible

It is possible to split the definition of a class or a struct, or an interface over two or more source files. Each source file contains a section of the class definition, and all parts are combined when the application is compiled

You should create a inherited class to achieve your goal

public class MyOrderProcessingService : OrderProcessingService
{
    public override PlaceOrderResult PlaceOrder(ProcessPaymentRequest processPaymentRequest) { //....
}