Some times you write classes, inherit from them and create properties to cast things from base class to your known types.
Like this
public abstract class BaseClass
{
private SomeClass backingField;
public SomeClass Property
{
get { return backingField; }
set
{
if (backingField == value)
return;
backingField = value;
// do other stuff
}
}
public BaseClass(SomeClass someClass)
{
Property = someClass;
}
}
public class DerivedClass : BaseClass
{
public OtherClass Derived => (OtherClass)Property;
public DerivedClass(OtherClass otherClass) : base(otherClass)
{
}
}
And you know that this is a huge amount of stuff you have to keep up with (every new derived class needs a property like this if you want it to strongly typed). My solution to this is simple: Just create a generic gerived class and new-override the Property.
public abstract class BaseClass<TClass> : BaseClass where TClass : SomeClass
{
public new SomeClass Property
{
get { return (TClass)base.Property; }
set { base.Property = value; }
}
public BaseClass(TClass tClass) : base(tClass)
{
}
}
And your derived class now looks like:
public class DerivedClass : BaseClass<OtherClass>
{
public DerivedClass(OtherClass otherClass) : base(otherClass)
{
}
}
Simple enough for every project to implement this. Has been a massive time saver in one of my projects.