Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

abstract classes in C#

Tags:

c#

c#-4.0

I want to create an abstract class in C#. Currently, I have this class in C#:

public class CreditReportViewModel
{
    public Person Person { get; set; }       
    public DateTime ReportDate { get; set; }
    public string PersonalAddress { get; set; }
    public string EmployerAddress { get; set; }
}

I want to make it abstract class and two other classes will inherit it. Do I just need to place abstract keyword with class to need to change properties as well. What about classes which will inherit this class. What need to be changed in these classes?

Please suggest.

like image 607
DotnetSparrow Avatar asked Dec 08 '25 12:12

DotnetSparrow


2 Answers

All you need to do is mark the class as abstract:

public abstract class CreditReportViewModel
{
    public Person Person { get; set; }       
    public DateTime ReportDate { get; set; }
    public string PersonalAddress { get; set; }
    public string EmployerAddress { get; set; }
}
like image 176
Daren Thomas Avatar answered Dec 10 '25 00:12

Daren Thomas


The only thing needed to make the class abstract is to add the keyword:

public abstract class CreditReportViewModel
{
    public Person Person { get; set; }       
    public DateTime ReportDate { get; set; }
    public string PersonalAddress { get; set; }
    public string EmployerAddress { get; set; }
}

In this case, implementing classes do not need to add any additional implementation:

class Derived : CreditReportViewModel { }

If you want to make members abstract as well, same thing goes there:

public abstract class CreditReportViewModel
{
    public Person Person { get; set; }       
    public DateTime ReportDate { get; set; }
    public string PersonalAddress { get; set; }
    public string EmployerAddress { get; set; }
    public abstract float MakeSomeCalculation();
}

public class Derived : CreditReportViewModel
{
    public override float MakeSomeCalculation()
    {
         // This method must be implemented in the derived class
    }
}

The typical case is that the abstract base class exposes some abstract members that need to be implemented by derived classes.

like image 28
Fredrik Mörk Avatar answered Dec 10 '25 00:12

Fredrik Mörk