Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Classes and base class inheritance in C#

Tags:

c#

inheritance

I have a class in C# like so:

public class BarChart
{
    public BarData BarChartData;
    public BarStyle BarChartStyle;

    public BarChart(BarData data, BarStyle style)
    {
        this.BarChartData = data;
        this.BarChartStyle = style;
    }

    string _uniqueName;
    public string UniqueName
    {
        get { return this._uniqueName; }
        set { this._uniqueName = value; }
    }
    string _rowNumber;
    public string RowNumber
    {
        get { return this._rowNumber; }
        set { this._rowNumber = value; }
    }

I want to create a class called Chart that will have all of the properties that BarChart class has. For example:

Chart someChart = new Chart(BarChart);
string name = someChart.UniqueName

I am relatively new to C# and the concept of inheritance is a little bit foreign to me. At the end of the day I will have multiple different chart types like LineChart, BarChart, etc., but I also want to be able to move them around and sort them like so:

List<Chart> groupedCharts = listOfCharts
.GroupBy(u => u.RowNumber)
.Select(grp => grp.ToList())
.ToList();

...hence the idea to throw them into generic Chart class for easy use with LINQ.

How would I go about setting that up?

like image 639
konrad Avatar asked Nov 13 '15 17:11

konrad


People also ask

What is class inheritance in C?

Inheritance is one of the key features of Object-oriented programming in C++. It allows us to create a new class (derived class) from an existing class (base class). The derived class inherits the features from the base class and can have additional features of its own.

What is base class inheritance?

The class whose members are inherited is called the base class, and the class that inherits those members is called the derived class. A derived class can have only one direct base class. However, inheritance is transitive.

What is classes and inheritance?

Inheritance is the procedure in which one class inherits the attributes and methods of another class. The class whose properties and methods are inherited is known as the Parent class. And the class that inherits the properties from the parent class is the Child class.

What is base class in C?

Base Class: A base class is a class in Object-Oriented Programming language, from which other classes are derived. The class which inherits the base class has all members of a base class as well as can also have some additional properties.


1 Answers

Create an abstract Chart class:

abstract class Chart
{
    // Shared properties
}

Then inherit it:

class BarChart : Chart
{
    // Bar chart properties
}

Then you can create it as:

Chart someChart = new BarChart();
like image 155
Marco Fatica Avatar answered Oct 03 '22 10:10

Marco Fatica