ViewModel Inheritance

Tom Meier 140 Reputation points
2024-05-08T15:24:59.8466667+00:00

Hi friends, I am trying to use inheritance in my ViewModel Class by adding the viewmodel EmployeeEditViewModel but I get a compilation error stating Class 'PayerEditViewModel' cannot have multiple base classes: 'ObservableObject' and "EmployeeEditViewModel'. Obviously I am using the community toolkit.

public partial class PayerEditViewModel: ObservableObject, IQueryAttributable,EmployeeEditViewModel

.NET MAUI
.NET MAUI
A Microsoft open-source framework for building native device applications spanning mobile, tablet, and desktop.
2,999 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,409 questions
0 comments No comments
{count} votes

Accepted answer
  1. Bruce (SqlWork.com) 58,126 Reputation points
    2024-05-08T20:10:12.85+00:00

    c# only allow inheritance from one base class. All others must be an interface. this generally requires you to define your class hierarchy correctly.

    If you changed EmployeeEditViewModel to inherit from ObservableObject, then PayerEditViewModel would also inherit. but Payer inheriting from Employee this does not seem correct, is a Payer always an Employee? Maybe there should be a common root.

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Q&A Assist
    2024-05-08T15:24:59.8566667+00:00
    AI generated content. This question contains an answer created with AI from Q&A Assist. Learn more

    The error message you are seeing indicates that you cannot have multiple base classes for your PayerEditViewModel class. In this case, you are trying to inherit from both ObservableObject and EmployeeEditViewModel.

    To resolve this error, you should consider using composition instead of inheritance. Instead of having PayerEditViewModel inherit from EmployeeEditViewModel, you can create an instance of EmployeeEditViewModel inside PayerEditViewModel and delegate to it as needed.

    Here's an example of what that might look like:

    public partial class PayerEditViewModel : ObservableObject, IQueryAttributable
    {
        private readonly EmployeeEditViewModel _employeeEditViewModel;
    
        public PayerEditViewModel()
        {
            _employeeEditViewModel = new EmployeeEditViewModel();
        }
    
        // Delegate to EmployeeEditViewModel as needed
        public string EmployeeName
        {
            get => _employeeEditViewModel.EmployeeName;
            set => _employeeEditViewModel.EmployeeName = value;
        }
    
        // Other properties and methods for PayerEditViewModel
    }
    

    This way, you can still use the functionality provided by EmployeeEditViewModel without having to inherit from it directly.


    References:

    0 comments No comments