What is the advantage of partial classes over inheritance?

C # has the concept of partial classes. One instance I saw is used in WSDL

s. Visual Studio can contact the server to find the service and automatically generate a partial class based on that. Visual Studios will then provide you with an empty partial class to match this so you can add your own code.

I find this approach is rather confusing. Is there any advantage for partial classes over inheritance?

+3


source to share


4 answers


Partial classes are designed to solve a specific problem - solving the problem of separating generated and hand-coded code. Without partial classes, programmers needed to either refrain from modifying the generated classes or rely on a design pattern to achieve separation.

One very important point is that the generated parts of the partial classes have an implementation. This distinguishes them from interfaces that do not contain implementation.



In a way, this makes them look like an abstract class without making them abstract. You are allowed to extend and change functionality without subclassing.

+6


source


Partial class:
You can define a class in multiple files in one project. You can create a file containing a method, another file contains properties, etc. At compile time it will be the same as you create one big file containing everything.

More about partial class and method



Inheritance:
You can extend the functionality of an existing class both within one project and in another project. With inheritance, you can extend a function, function, etc. An existing class in a new class.

+1


source


Consistent partial classes are much more about splitting a class definition across multiple source files than inheritance.

It always seemed to me that the main reason for them was that frameworks could generate boiler stove code for you, and you could also add methods without overriding your code with a visual studio built to access data or create web services.

I have always found it wrong and lazy Microsoft.

0


source


this is an invitation to the developer to implement the method, if required, in the second declaration for the partial class. You can better support your application by compacting large classes. Let's say you have a class with multiple interfaces, so you can create multiple source files depending on the interface. It is easy to understand and maintain an implemented interface where the source file has a partial class. Consider the following piece of code.

  public interface IRegister
  {
//Register related function
  }

  public interface ILogin
  {
//Login related function
  }

  //UserRegister.cs file
 public partial classUser : IRegister, ILogin
  {
//implements IRegister interface
  } 

 //UserLogin.cs file
 public partial classUser
 {
//implements ILogin interface
 }

      

-1


source







All Articles