SverkerSbrg
SverkerSbrg

Reputation: 503

Base class static method using constants of derived class

I'm a bit new to c#. Is the following pattern viable or do I need to rethink things:

public abstract class Foo{
    abstract const Format Format;
    public static GetFormat(){
        return <Format configured by derived class> 
    }
}

public class JsonFoo:Foo{
    const Format Format = Format.JSON;
}

public class XmlFoo:Foo{
    const Format Format = Format.XML;
}

I've tried to resolve it several ways buy I always run in to static can not be abstract/virtual etc.

(The code above is just to illustrate the problem)

Edit:

So i want to build an abstract base class with most of my logic, and then create light weight derived classes. All most all of the operations are identical but with minor differences (such as using a different format (the real case is accessing different DbSets on a common DbContext)).

Some of the operations are very similar (in the DbSet context, find object by id, find all etc...)

Upvotes: 1

Views: 64

Answers (1)

burning_LEGION
burning_LEGION

Reputation: 13450

You've done strange construction. You should write something like:

public enum Format{XML,JSON}
public abstract class Foo
{
    public abstract Format Format { get; }
}
public class JsonFoo : Foo
{
    public override Format Format
    {
        get { return Format.JSON; }
    }
}
public class XmlFoo : Foo
{
    public override Format Format
    {
        get { return Format.XML; }
    }
}

Upvotes: 3

Related Questions