Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does C# support multiple inheritance 4.0?

Tags:

c#

inheritance

I recently took a practice C# skills test and one of the questions was,

Does C# support multiple inheritance?

I answered yes, and was was marked wrong. After some research online, its full of answers of why it is not supported:

Multiple inheritance support in C#

Why is Multiple Inheritance not allowed in Java or C#?

http://www.codeproject.com/Questions/652495/Why-does-csharp-doesnt-support-Multiple-inheritanc

Then I went and tried to replicate the error I should be getting when trying to inherit from a Class that already inherited from a Base Class, and there is no error. I am using console application, and I recently upgraded to .net 4.5, maybe things have changed?

Code for how I tested:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {

            Leo bk = new Leo();

            bk.avgWords();

            Console.ReadLine();

        }

        public void bubbleSort(int[] input)
        {

        }

        public void insertionSort(int[] input)
        {

        }
    }

    public class Gatsby : Books
    {


        public override void avgWords()
        {

            Console.WriteLine(5);

        }

    }

    public class Leo : Gatsby
    {


        public override void avgWords()
        {
            Console.WriteLine(7);
        }

    }

    public class Dicaprio : Leo
    {


    }

    public class Books
    {

        public int id { get; set; }
        public string title { get; set; }
        public string author { get; set; }

        public virtual void avgWords()
        {


            Console.WriteLine(3);
        }


    }
}
like image 358
Eduardo Dennis Avatar asked Feb 12 '26 02:02

Eduardo Dennis


1 Answers

Then I went and tried to replicate the error I should be getting when trying to inherit from a Class that already inherited from a Base Class, and there is no error. I am using console application, and I recently upgraded to .net 4.5, maybe things have changed?

No, that is still considered single inheritance. Your class only inherits from a single base class.

Some languages, like C++, allow you to inherit from more than one class. The C# version would be something like:

class Foo {} 
class Bar {}

// This is invalid in C#!
class Baz : Foo, Bar {}

However, that's not allowed.

Note that C# does allow you to implement multiple interfaces, however.

like image 190
Reed Copsey Avatar answered Feb 14 '26 14:02

Reed Copsey



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!