0

I'm trying to be able to call one subclass constructor or another, depending on the arguments values for the constructor:

public FlacFullContent(string path, bool isFlog=false)
{
    if (isFlog)
    {
        using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
        {
            Track theTrack = new Track(fs, "audio/ogg");
            // instead call base class constructor `base(fs, "audio/ogg")`
        }
    }
    else
    {
        // call base class constructor `base(path)`
    }
}

For a subclass public class FlacFullContent: Track.

Is that possible ? How ?

Soleil
  • 6,404
  • 5
  • 41
  • 61

1 Answers1

3

What you are trying to do is not possible in C# . However, there are several design patterns suited for this situation.

One option is not to use inheritance at all. If your subclass isn't overriding any methods of the base class and only varies in how it is constructed, then you could simply provide a static factory function.

Another option is to use the decorator pattern. This would allow you to inject a correctly configured Track object into your subclass and forward all unchanged data to it.

Additionally, you should be aware that putting a using block in a constructor is usually a bad idea. Whatever resource you initialize in the using will be disposed at the end of the block. That means that if the class needs to reference it elsewhere, it will already be disposed. If an object depends on disposable resources, you generally either want it to implement IDisposable itself, having the using block mirror the lifetime of the object, or initialize and dispose the resource in each method.

Nick Bailey
  • 3,078
  • 2
  • 11
  • 13
  • Decorator pattern is the best decision here. Composition is better than inheritance nowadays – Anton23 Mar 20 '22 at 17:50
  • IMHO the 'right' pattern would depend on context. Its very possible that `FlacFullContent` is totally redundant and the work could be done with the base class alone. – Nick Bailey Mar 20 '22 at 17:51