- If instead i use a interface i cannot count on specific fields or variables as it only takes methods. Is there any reason to use interfaces?
While this is basically true, interfaces may include getters and setters. So you can mimic variable members without actually using them.
Just a simple example:
interface IWeapon {
unsigned int CurrentAmmo { get; set; }
unsigned int MaxAmmo { get; }
TimeSpan ShootInterval { get; }
TimeSpan ReloadTime { get; }
string Name { get; }
void Reload();
}
- If i use derived classes and have a List with mixed items from different derived classes i would need some code that goes through each class and casts it to the proper class to use its unique abilities. How is this best handled?
That's exactly the reason for using polymorphism. If done right, your system will automatically call the apropriate member, without forcing casts or any special handling. Have a look at the virtual keyword.
Another short example:
class Drawable {
virtual void Draw(RenderClass renderer) {
}
}
// ...
foreach(Drawable d in Entities)
d.Draw(myRenderTarget);
Derived classes can now do one of two things:
Don't implement Drawable::Draw
which will essentially redirect all calls to the base class (i.e. default behavior).
Reimplement Drawable::Draw
using the override keyword to overwrite the default behavior.
If a member is marked as virtual
, you'll always call the most derived override
being available.
Using an abstract base class is similar, but compared to interfaces this allows you to already implement parts, while leaving others unimplemented (they'll have to be implemented in derived classes).