Home > OS >  How to enforce deriving classes to implement an abstract property but allow implementations to use c
How to enforce deriving classes to implement an abstract property but allow implementations to use c

Time:11-03

I am trying to enforce all classes deriving from class EducationalUnit to implement a "Content" property. This property needs to be a key value pair where the key is an int and the value can be either another class implementing EducationalUnit or another class I have called ContentBlock.

in EducationalUnit class i try to define an abstract property to take an Int and any Object key value pair.

public abstract Dictionary<int, Object> Content {get; set;}

And in the inheriting classes try to implement it:

public class Course : EducationalUnit
    {
        public override Dictionary<int, EducationalUnit> Content {get; set;}
    
        public Course () {
            this.Type = "Course";
        }
    }

However, when I try to do this I get 'Course.Content': type must be 'Dictionary<int, object>' to match overridden member 'EducationalUnit.Content' [Domain]csharp(CS1715).

I assumed since all classes inherit from Object this should have worked. Can someone tell me what am I doing wrong and a potential approach to implement this?

CodePudding user response:

You cannot override the type Dictionary<int, Object> with Dictionary<int, EducationalUnit>.

You could define a generic though, and make it work that way.

abstract class BaseClass<T>
{
    public abstract Dictionary<int, T> Content { get; set; }
}

class EducationalUnit { }

class Course : BaseClass<EducationalUnit>
{
    public override Dictionary<int, EducationalUnit> Content { get; set; } = new();

    public Course() 
    { }    
}

You could also override it with public override Dictionary<int, object> Content { get; set; } = new();, but then you can't access any of the variables, properties or methods you have on EducationalUnit, unless you cast it back to an EducationalUnit from object. But this really defeats the purpose of using inheritance.

  • Related