Partial class support vs Specify a base class

Laurent Guigon 311 Reputation points
2023-07-30T10:21:30.3333333+00:00

Hi,
I asked this question a few months ago.

The answer explained the difference between the two approaches.

Today, I'm wondering what the best practice is:

  • Should I always use the "Specify a base class" approach?
  • Or perhaps combine it with the partial class approach?
  • Or even use partial classes that inherit from a base class?

What are your advice regarding the "code behind" design?

If the third way is the best, can you give me a code sample showing how to implement this ?

Developer technologies | .NET | Blazor
{count} votes

2 answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 77,686 Reputation points Volunteer Moderator
    2023-07-31T17:18:57.37+00:00

    a base class is used for inheritance. Modern design practice is to avoid having a very deep inheritance tree, that is more than a base class and an inherited class. the main use case is a library class that allow user extension. as changes to the super classes can break an inherited class, this technique is considered fragile.

    partial classes allow the class definition to be split into multiple files. the main use case, is customizing auto generated code. the autogenerated code can be regenerated without deleting the custom code.

    interface design or composition is often preferred over inheritance.

    also you can use extension methods to extend a class.

    https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/extension-methods


  2. Laurent Guigon 311 Reputation points
    2023-08-09T10:26:03.1966667+00:00

    I found this topic on the net. If I understood it correctly, a good practice is to separate C# and Razor code by using a partial class (MyPage.razor + MyPage.razor.cs, which is the partial class). If you use the same instructions in several pages, then you should factorize it! Create a base class and use inheritance in the .razor.cs code.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.