Can't abstract replace partial?

200 views Asked by At

The biggest argument I've seen so far for partial classes is in the case of auto-generated code.

From a Java perspective, I don't see why this can't simply be done using abstract classes, can't the auto-generated code simply be an abstract class with protected abstract methods that it expects the user to override?

Aside from the auto-generated code cases, every other case I saw was either extremely rare (and the coders were just using partial as a hack), or it can also be solved using abstract or some other concept that already exists.

2

There are 2 answers

3
usr On

Inheritance is observable on the compiled assembly while partial is not. This makes inheritance unsuitable for libraries where you need to control the surface area tightly. The .NET BCL could never use this for example.

It is also a hack because inheritance is not meant to stitch together classes. It is primarily meant as a means to create substitutability and abstraction.

partial is meant for exactly this use case. The parts of a partial class can refer to each other which is not possible with inheritance.

Partial methods allow you to create methods that might exist in the compiled result, or not. LINQ to SQL uses them to give you callback hooks into various parts of the DataContext and entity classes. If you don't use them there is no performance cost at all because partial methods that are declared but never defined are just deleted.

1
Magnus A On

For me, partial classes is a way to devide classes into more logical parts. Sometimes cause they are partly auto generated, sometimes because they are really complex.

Abstract is for inheritage, and why use that when nothing is really "shared".