Search code examples
c#derived-class

C#: Pass derived class as parameter


I have a base class that does calculations on image sizes. I'm deriving a class from that and have predefined image sizes that will be used in my code. While what I have works, I have a strong feeling that I'm not doing it properly.

Ideally, I'd like to just pass DerviedClass.PreviewSize as the parameter to GetWidth without having to create an instance of it.

class Program
{
    static void Main(string[] args)
    {
        ProfilePics d = new ProfilePics();
        Guid UserId = Guid.NewGuid();

        ProfilePics.Preview PreviewSize = new ProfilePics.Preview();
        d.Save(UserId, PreviewSize);
    }
}

class ProfilePicsBase
{
    public interface ISize
    {
        int Width { get; }
        int Height { get; }
    }

    public void Save(Guid UserId, ISize Size)
    {
        string PicPath = GetTempPath(UserId);
        Media.ResizeImage(PicPath, Size.Width, Size.Height);
    }
}

class ProfilePics : ProfilePicsBase
{
    public class Preview : ISize
    {
        public int Width { get { return 200; } }
        public int Height { get { return 160; } }
    }
}

Solution

  • It seems to me that you want a more flexible implementation of ISize - having an implementation which always returns the same value seems fairly pointless. On the other hand, I can see that you want an easy way of getting the size that you always use for a preview. I would do it like this:

    // Immutable implementation of ISize
    public class FixedSize : ISize
    {
        public static readonly FixedSize Preview = new FixedSize(200, 160);
    
        private readonly int width;
        private readonly int height;
    
        public int Width { get { return width; } }
        public int Height { get { return height; } }
    
        public FixedSize(int width, int height)
        {
            this.width = width;
            this.height = height;
        }
    }
    

    You could then write:

    ProfilePics d = new ProfilePics();
    Guid userId = Guid.NewGuid();
    
    d.Save(userId, FixedSize.Preview);
    

    This would reuse the same instance of FixedSize whenever you called it.