Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

creating new class from existing class: inheritance or partial classes?

Tags:

c#

I have a class that defines an object like this:

public class MyClass{

   public int TheInt { get; set; }

   public void SomeMethod() { ... }
}

Actually, there are several more properties and methods. Now I want to create a new class MyEnhancedClass that has all the properties and methods of MyClass and that also has 2 methods and 4 properties of its own.

For now, my code has two distinct classes that look very similar; I'm looking to refactor these classes and I'm wondering about partial classes and inheritance. What the best way to do this? Inheritance or partial classes? I know this is a basic OOP question but please bear with me.

Thanks for your suggestions.

like image 442
frenchie Avatar asked Mar 20 '26 21:03

frenchie


1 Answers

I assume you're talking about inheritance. To inherit one class from another you use the following notation in C#:

public class MyExtendedClass : MyClass
{
    // custom code
}

Update: Even though inheritance might not be the best solution in every case (see Oded's comments below), partial classes should be avoided because they would be even worse. They are not part of the language but syntactic sugar that encourages the introduction of various code smells.

like image 168
Dennis Traub Avatar answered Mar 22 '26 12:03

Dennis Traub



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!