Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't abstract replace partial?

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.

like image 882
Morad Avatar asked Feb 14 '23 12:02

Morad


1 Answers

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.

like image 115
usr Avatar answered Feb 24 '23 06:02

usr