36

I have a class in Model in my MVC project like this.

public partial class Manager : Employee
{
    public string Name {get;set;}
    public int Age {get;set;}
}

And this class I have in App_Code folder in the same project. Now I want to know whether my this class is also need to get inherit from the Employee class or Not?

public partial class Manager 
{
    public void SaveEmployee();
}

I have to do this because my client want me to move all the methods in App_Code folder which are dealing with database.

And yes both these classes are sharing the same namespace.

Jitender Kumar
  • 2,439
  • 4
  • 29
  • 43

2 Answers2

44

That's a single class defined across multiple declarations, not two different classes. You only need to define the inheritance model in a single declaration, e.g.:

public class Foo { }

//Bar extends Foo
public partial class Bar : Foo { }

public partial class Bar {  }

However, if you were to try the following, you'd generate a compiler error of "Partial declarations of 'Bar' must not specify different base classes":

public class Foo { }

public partial class Bar : Foo { }

public partial class Bar : object {  }
Preston Guillot
  • 6,493
  • 3
  • 30
  • 40
  • You are right Preston, But Now I have got another problem. It seems that I cannot extend the partial class from Model to App_Code folder becuase now I am getting error when I try to access the property of model class :"Compiler Error CS1061- This error occurs when you try to call a method or access a class member that does not exist." But it works fine if I put these both parital classes in model. – Jitender Kumar Feb 15 '14 at 07:35
  • @PrestonGuillot what if your base which you are inheriting from has a constructor? I can't seem to create my partial classes without having to call the base constructor from both, even though I'd expect I only have to from one? – Chucky Jan 24 '17 at 15:41
  • @Chucky I'm not clear on your exact issue without seeing your code - it sounds like it'd be worth opening a new question, though. Conceptually, I'm not sure what you mean by "having to call the base constructor from both" - all classes have a constructor in C#, if you are extending a class by providing a new constructor and you want to ensure the base class' constructor is called, you'd do that in your new class' constructor, but you'd only need the constructor definition in a single file of a partial class. – Preston Guillot Jan 25 '17 at 17:26
  • 2
    I figured out my issue as to why my partial class wasn't working with one constructor - mismatching namespaces. – Chucky Feb 28 '17 at 12:06
2

Yes, the other part of the partial class is still the same class so it does inherit from Employee.

Iain Holder
  • 14,172
  • 10
  • 66
  • 86