Wednesday, April 18, 2012

C# interface with implementation without abstract class?

I am writing a library and I want to have an interface



public interface ISkeleton
{
IEnumerable<IBone> Bones { get; }
void Attach(IBone bone);
void Detach(IBone bone);
}


The Attach() and Detach() implementation actually should be the same for every ISkeleton. Thus, it could essentially be:



public abstract class Skeleton
{
public IEnumerable<IBone> Bones { get { return _mBones; } }

public List<IBone> _mBones = new List<IBone>();

public void Attach(IBone bone)
{
bone.Transformation.ToLocal(this);
_mBones.add();
}

public void Detach(IBone bone)
{
bone.Transformation.ToWorld(this);
_mBones.Remove(bone);
}
}


But C# doesn't allow multiple inheritance. So among various issues, users have to remember to inherit from Skeleton every time they want to implement Skeleton.



I could use extension methods



public static class Skeleton
{
public static void Attach(this ISkeleton skeleton, IBone bone)
{
bone.Transformation.ToLocal(skeleton);
skeleton.Bones.add(bone);
}

public static void Detach(this ISkeleton skeleton, IBone bone)
{
bone.Transformation.ToWorld(this);
skeleton.Bones.Remove(bone);
}
}


But then I need to have



public interface ISkeleton
{
ICollection<IBone> Bones { get; }
}


Which I do not want, because it is not covariant and users can bypass the Attach() and Detach() methods.



QUESTION: Must I really use an abstract Skeleton class or are there any or tricks and methods?





No comments:

Post a Comment