A. Write it twice
Write the method twice. There should be minimal duplication needed:
private void RescaleFont(Type1 ctrl, double scale)
{
ctrl.Font = GetFont(scale));
}
private void RescaleFont(Type2 ctrl, double scale)
{
ctrl.Font = GetFont(scale));
}
Please note that only setting the font is duplicated and GetFont
is not duplicated, it's just called from two places.
B. Add an interface
private void RescaleFont(IWithFont ctrl, double scale)
{
ctrl.Font = GetFont(scale));
}
C. Control.Font Property
Are you sure that your controls aren't inheriting from the same base class, something like System.Windows.Forms.Control
?
private void RescaleFont(System.Windows.Forms.Control ctrl, double scale)
{
ctrl.Font = GetFont(scale));
}
D. Use reflection
using System.Linq.Expressions;
using System.Reflection;
class A
{
public Font Font { get; set; } = new Font("Arial", 4);
}
class B
{
public Font Font { get; set; } = new Font("Arial", 3);
}
class C
{
}
static void SetFont<T>(Font toSet, T target, Expression<Func<T, Font>> outExpr)
{
var expr = (MemberExpression)outExpr.Body;
var prop = (PropertyInfo)expr.Member;
prop.SetValue(target, toSet, null);
}
Then:
var exampleFont = new Font("Arial", 11);
var a = new A();
SetFont(exampleFont, a, x => x.Font);
var b = new B();
SetFont(exampleFont, b, x => x.Font);
var c = new C();
SetFont(fontX, c, x => x.Font); // error CS1061: 'Program.C' does not contain a definition for 'Font'