Using Generics in c# in order to avoid code duplication - c#

(Language is c# with VS 2008)
I have the following problem:
There are a number of structs (provided as is from 3rd party) that all implement certain methods with the same signatures.
I would like to wrap these struct with wrapper classes that implement a certain interface so that these classes can be treated in a uniform way.
Example:
interface AnInterface
{
void DoSomething();
}
struct Struct1
{
public void DoSomething();
}
class Struct1Wrapper : AnInterface
{
private Struct1 m_struct;
public override void DoSomething() // AnInterface implementation
{
m_struct.DoSomething();
}
}
Note that Struct1 DoSomething method is concrete while Struct1Wrapper implements it through an interface for easier handling.
The same goes with Struct2 and so on - the code of StructXWrapper is the same except for Struct1 replaced by StructX
I have tried using generics in order to avoid code duplication:
class GenericStructWrapper<AStruct> : AnInterface
{
private AStruct m_struct;
public override void DoSomething() // AnInterface implementation
{
m_struct.DoSomething();
}
}
But this won't work since the compiler doesn't have a notion about AStruct DoSomething() method.
Any other idea how to implement this without duplicating the code of Struct1Wrapper?
Perhaps there is some macro-like feature or some use of reflection?
Thanks,
Ury Jamshy.

You can take a Action<AStruct> in the class constructor that takes the method.
You can then create instances like new GenericStructWrapper<Struct1>(s => s.DoSomething())

C# doesn't safely support structural typing (except in certain unusual contexts), so there's no way to make this completely safe without code-duplication. You either have to go with SLak's technique of asking the client to provide a delegate (will probably involve repeating the same lambda expression over and over) or to assume that the underlying types will satisfy the contract of containing a public void DoSomething() method.
Going with the second option, here's one way using dynamic in C# 4:
public class StructWrapper: AnInterface
{
private readonly dynamic m_struct;
public StructWrapper(object myStruct)
{
m_struct = myStruct;
}
public void DoSomething()
{
m_struct.DoSomething();
}
}
Now, you could try to make this class generic, with the underlying-structure type being the generic-type argument, but that will probably not help you all that much unless you also want to perform structure-specific operations on the wrapped-type. Here's an example of that, with reflection and delegates (C# 3 compatible):
public class StructWrapper<T> : AnInterface where T : struct
{
private readonly Action action;
// deliberately exposed
public T UnderlyingStruct { get; private set; }
public StructWrapper(T underlyingStruct)
{
UnderlyingStruct = underlyingStruct;
action = (Action)Delegate.CreateDelegate
(typeof(Action), underlyingStruct, "DoSomething");
}
public void DoSomething()
{
action();
}
}
Note that you can mix and match the two techniques mentioned above, e.g. reflection but without generics.
Usage:
AnInterface wrapper1 = new StructWrapper(new Struct1());
wrapper1.DoSomething();
StructWrapper<Struct1> wrapper2 = new StructWrapper<Struct1>(new Struct1());
wrapper2.DoSomething();
Struct1 s = wrapper2.UnderlyingStruct; // generics help here
s.SomeOtherMethod();

There is a syntax for this:
class GenericStructWrapper<AStruct> : AnInterface where AStruct : AnInterface
{
private AStruct m_struct;
public override void DoSomething() // AnInterface implementation
{
m_struct.DoSomething();
}
}
This says that AStruct must implement AnInterface

Related

Struct implementing interface function without boxing

Background
I want to allow a class instance to register callbacks with an event system while avoiding boxing.
A bit of background: I have a home-grown Event System structured as shown below:
class EventSystem
{
// registers a struct instance with an event
// when the event triggers, it calls the run() method and passes in some info
public void Register(ICallback callbackStruct, Event e);
}
public enum Event
{
SOME_EVENT,
SOME_OTHER_EVENT
}
interface ICallback
{
void Run(string data);
}
An example implementation of this is:
class Example
{
private Behaviour_A a = new Behaviour_A();
private Behaviour_B b = new Behaviour_B();
public Example()
{
eventSystem.Register(a, SOME_EVENT);
eventSystem.Register(b, SOME_OTHER_EVENT);
}
struct Behaviour_A : ICallback
{
void Run(string data)
{
// some behvaiour
}
}
struct Behaviour_B : ICallback
{
void Run(string data)
{
// some other behvaiour
}
}
}
Pros
I like this solution because it makes use of composition rather than inheritance (and also supports multiple callback behaviours for the same event in one instance), and I'd prefer to use structs over anonymous functions since they are stateful and might be re-used with different parameters and a few other reasons.
Cons
However, I dislike this solution because it requires boxing each time the struct is passed around and I'm trying to avoid heap allocations as much as possible.
Question
Is there any way I can implement custom behaviouron a struct as shown while avoiding boxing?
The key to avoiding boxing when using structs that implement interfaces is to use interface-constrained generics.
If one has a function that receives an argument of type T, where T is constrained to IEquatable<T>, then the .NET runtime will generate a separate machine code version of that function for every distinct structure type that is passed to it, and within those machine-code versions of the function no boxing will be required.
It's not a answer but just a suggestion . Decoupling Data and Behaviour , it's more clean design. and make sure Register param is a class. this way is good to handle boxing by you self. maybe use object pool or something. This way can handle unnecessary GC.
public class EventSystem
{
// here make sure T is a class , not struct.
public void Register<T>(T callbackStruct, Event e) where T : class , ICallback
{
}
}
public enum Event
{
SOME_EVENT,
SOME_OTHER_EVENT
}
public interface ICallback
{
void Run(string data);
}
class Example
{
private Behaviour_A a = new Behaviour_A();
private Behaviour_B b = new Behaviour_B();
public Example()
{
EventSystem eventSystem = new EventSystem();
staticAObj.PutData(a);
eventSystem.Register(staticAObj, Event.SOME_EVENT);
eventSystem.Register(b, Event.SOME_OTHER_EVENT);
}
struct A
{
}
struct B
{
}
class Behaviour_A : ICallback
{
A a;
public void Run(string data)
{
// some behvaiour
}
}
class Behaviour_B : ICallback
{
B b;
public void Run(string data)
{
// some other behvaiour
}
}
}
Unless I missed something obvious, your registration method should just add the ref modifier:
public void Register(ref ICallback callbackStruct, Event e);
This guarantees your structure will not be copied on the stack because only the reference will be copied, and your original struct can be used through that. The heap remains intact.
You will have to modify the callsite:
eventSystem.Register(ref a, SOME_EVENT);
eventSystem.Register(ref b, SOME_OTHER_EVENT);
And, based on Guru's comments, this might be a solution: further modify the signature to
void Register<T>(ref T callbackStruct, Event e) where T : ICallback;
or
void Register<T>(ref T callbackStruct, Event e) where T : struct, ICallback;
to remove the box, but you're possibly adding brittleness to this code.
For yourEventSystem to register this it would need to be either non-abstract and provide the method below, or it would need a subclass that implements
public void Register<T>(ref T callbackStruct, Event e) where T : struct, ICallback
{}

Why can a class implement its own private nested interface in C#?

The following code is a valid C# construct that compile juste fine.
public class Weird : Weird.IWeird
{
private interface IWeird
{
}
}
What would be the possible uses of this?
Edit: This question is more specific that this one: "What is a private interface?". It shows that it's possible to implement a private interface from the parent type itself, which seems to be rather pointless. The only use I can think of would be a weird case of interface segregation where you would want to pass an instance of the parent class to a nested class instance as IWeird.
This is probably one of these situations in compiler development when prohibiting something has a higher cost than allowing it. Prohibiting this use would require writing and maintaining code to detect this situation, and report an error; if the feature works as-is, this is an additional work for the team, and it could be avoided. After all, perhaps someone with good imagination could figure out a way to use the feature.
As far as a useful example goes, one potential use is to make another implementation in the class, and use it as an alternative without exposing it to the users of the API:
public class Demo : Demo.Impl {
// Private interface
private interface Impl {
public bool IsValidState {get;}
void DoIt();
}
// Implementation for the error state
private class Error : Impl {
public bool IsValidState { get { return false; } }
public void DoIt() {
Console.WriteLine("Invalid state.");
}
}
private readonly string name;
// Implementation for the non-error state
public bool IsValidState { get { return true; } }
public void DoIt() {
Console.WriteLine("Hello, {0}", name);
}
// Constructor assigns impl depending on the parameter passed to it
private readonly Impl impl;
// Users are expected to use this method and property:
public bool IsValid {
get {
return impl.IsValidState;
}
}
public void SayHello() {
impl.DoIt();
}
// Constructor decides which impl to use
public Demo(string s) {
if (s == null) {
impl = new Error();
} else {
impl = this;
name = s;
}
}
}
As far as best practices go, this design is questionable at best. In particular, I would create a second nested class for the non-error implementation, rather than reusing the main class for that purpose. However, there is nothing terribly wrong with this design (apart from the fact that both IsValidState and DoIt are visible) so it was OK of the C# team to allow this use.

Exposing different interfaces from single class

We are trying to build some kind of a layer above the DAL in order to expose an interface of a certain repository methods using generics.
For example:
public interface A
{
void Do_A();
}
public interface B
{
void Do_B();
}
public void Main()
{
Exposer<A>.Do_A();
Exposer<B>.Do_B();
}
Is it possible to do that ?
Tecnically, that isn't a "single class", since Exposer<A> is a different Type to Exposer<B>; however, ultimately, this doesn't look much different to most IoC/DI containers... if this was, say, StructureMap (purely for an example), you might consider:
container.GetInstance<A>().Do_A();
container.GetInstance<B>().Do_B();
you would, of course, need to configure the container to know where the concrete A and B implementations are coming from! Which for StructureMap is shown here, but there are plenty to choose from.
If you mean directly, then: no. You cannot have:
class Exposer<T> : T {...} // non-working code to implement the interface T
You can, however, have some class:
class Exposer : A, B {...}
and just cast:
A a = Exposer;
a.Do_A();
B b = Exposer;
b.Do_B();
A type Foo<T> cannot implement (or extend) the actual T, as T is unknown at compile time. What you could do is expose a T as a property, and invoke methods on it. However, as Ondrej wrote, the question may be a little unclear.
Are you describing IoC when you write?
Exposer<A>.Do_A();
Your Exposer class makes me think to StructureMap API:
ObjectFactory.GetInstance<T>().Do_A();
If you want to get rid of the keyword new and get in a generic way an instance for a specified interface, take a look to this article or check StructureMap
To choose which interface implementation you want when consuming a given class, you don't use generics, you just cast the class to the interface:
public interface A
{
void Do_A();
}
public interface B
{
void Do_B();
}
public class Exposer : A, B
{
public void Do_A() { ; }
public void Do_B() { ; }
}
public void Main()
{
// the casts are redundant here,
// because the interface implementation
// is implicit
((A)Exposer).Do_A();
((B)Exposer).Do_B();
}
If you want to exclude members that are not implementations of members of the given interface, use explicit implementation:
public class Exposer : A, B
{
void A.Do_A() { ; }
void B.Do_B() { ; }
}
public void Main()
{
// the casts are now required;
// otherwise, you'll get a compiler error
// telling you that the method is inaccessible
((A)Exposer).Do_A();
((B)Exposer).Do_B();
}

Implementing few methods of a interface class-C#

Is it possible in C# to have a class that implement an interface that has 10 methods declared but implementing only 5 methods i.e defining only 5 methods of that interface??? Actually I have an interface that is implemented by 3 class and not all the methods are used by all the class so if I could exclude any method???
I have a need for this. It might sound as a bad design but it's not hopefully.
The thing is I have a collection of User Controls that needs to have common property and based on that only I am displaying them at run time. As it's dynamic I need to manage them for that I'm having Properties. Some Properties are needed by few class and not by all. And as the control increases this Properties might be increasing so as needed by one control I need to have in all without any use. just the dummy methods. For the same I thought if there is a way to avoid those methods in rest of the class it would be great. It sounds that there is no way other than having either the abstract class or dummy functions :-(
You can make it an abstract class and add the methods you don't want to implement as abstract methods.
In other words:
public interface IMyInterface
{
void SomeMethod();
void SomeOtherMethod();
}
public abstract class MyClass : IMyInterface
{
// Really implementing this
public void SomeMethod()
{
// ...
}
// Derived class must implement this
public abstract void SomeOtherMethod();
}
If these classes all need to be concrete, not abstract, then you'll have to throw a NotImplementedException/NotSupportedException from inside the methods. But a much better idea would be to split up the interface so that implementing classes don't have to do this.
Keep in mind that classes can implement multiple interfaces, so if some classes have some of the functionality but not all, then you want to have more granular interfaces:
public interface IFoo
{
void FooMethod();
}
public interface IBar()
{
void BarMethod();
}
public class SmallClass : IFoo
{
public void FooMethod() { ... }
}
public class BigClass : IFoo, IBar
{
public void FooMethod() { ... }
public void BarMethod() { ... }
}
This is probably the design you really should have.
Your breaking the use of interfaces. You should have for each common behaviour a seperate interface.
That is not possible. But what you can do is throw NotSupportedException or NotImplementedException for the methods you do not want to implement. Or you could use an abstract class instead of an interface. That way you could provide a default implementation for methods you choose not to override.
public interface IMyInterface
{
void Foo();
void Bar();
}
public class MyClass : IMyInterface
{
public void Foo()
{
Console.WriteLine("Foo");
}
public void Bar()
{
throw new NotSupportedException();
}
}
Or...
public abstract class MyBaseClass
{
public virtual void Foo()
{
Console.WriteLine("MyBaseClass.Foo");
}
public virtual void Bar()
{
throw new NotImplementedException();
}
}
public class MyClass : MyBaseClass
{
public override void Foo()
{
Console.WriteLine("MyClass.Foo");
}
}
While I agree with #PoweRoy, you probably need to break your interface up into smaller parts you can probably use explicit interfaces to provider a cleaner public API to your interface implementations.
Eg:
public interface IPet
{
void Scratch();
void Bark();
void Meow();
}
public class Cat : IPet
{
public void Scratch()
{
Console.WriteLine("Wreck furniture!");
}
public void Meow()
{
Console.WriteLine("Mew mew mew!");
}
void IPet.Bark()
{
throw NotSupportedException("Cats don't bark!");
}
}
public class Dog : IPet
{
public void Scratch()
{
Console.WriteLine("Wreck furniture!");
}
void IPet.Meow()
{
throw new NotSupportedException("Dogs don't meow!");
}
public void Bark()
{
Console.WriteLine("Woof! Woof!");
}
}
With the classes defined above:
var cat = new Cat();
cat.Scrach();
cat.Meow();
cat.Bark(); // Does not compile
var dog = new Dog();
dog.Scratch();
dog.Bark();
dog.Meow(); // Does not compile.
IPet pet = new Dog();
pet.Scratch();
pet.Bark();
pet.Meow(); // Compiles but throws a NotSupportedException at runtime.
// Note that the following also compiles but will
// throw NotSupportedException at runtime.
((IPet)cat).Bark();
((IPet)dog).Meow();
You can simply have the methods you don't want to impliment trow a 'NotImplementedException'. That way you can still impliment the interface as normal.
No, it isn't. You have to define all methods of the interface, but you are allowed to define them as abstract and leave the implementation to any derived class. You can't compile a class that says that implements an interface when in fact it doesn't.
Here is a simple stupid example of what I meant by different interfaces for different purposes. There is no interface for common properties as it would complicate example. Also this code lacks of many other good stuff (like suspend layout) to make it more clear. I haven't tried to compile this code so there might be a lot of typos but I hope that idea is clear.
interface IConfigurableVisibilityControl
{
//check box that controls whether current control is visible
CheckBox VisibleCheckBox {get;}
}
class MySuperDuperUserControl : UserControl, IConfigurableVisibilityControl
{
private readonly CheckBox _visibleCheckBox = new CheckBox();
public CheckBox VisibleCheckBox
{
get { return _visibleCheckBox; }
}
//other important stuff
}
//somewhere else
void BuildSomeUi(Form f, ICollection<UserControl> controls)
{
//Add "configuration" controls to special panel somewhere on the form
Panel configurationPanel = new Panel();
Panel mainPanel = new Panel();
//do some other lay out stuff
f.Add(configurationPanel);
f.Add(mainPanel);
foreach(UserControl c in controls)
{
//check whether control is configurable
IConfigurableOptionalControl configurableControl = c as IConfigurableVisibilityControl;
if(null != configurableControl)
{
CheckBox visibleConfigCB = configurableControl.VisibleCheckBox;
//do some other lay out stuff
configurationPanel.Add(visibleConfigCB);
}
//do some other lay out stuff
mainPanel.Add(c);
}
}
Let your Interface be implemented in an abstract class. The abstract class will implement 5 methods and keep remaining methods as virtual. All your 3 classes then should inherit from the abstract class. This was your client-code that uses 3 classes won't have to change.
I want to add dynamically the control to my form as I have that as my requirement. I found the code from here. I edited it as I needed. So I have the IService class that has the common properties. This is implemented by the User Controls. Which are shown at runtime in different project. Hmmm for that I have different common interface that has properties which are used by the project for displaying the controls. Few controls need some extra methods or peoperties for instance to implement a context menu based on user selection at runtime. i.e the values are there in the project which will be passed as the properties to the control and it will be displayed. Now this menu is there only for one control rest of them don't have this. So I thought if there is a way to not to have those methods in all class rather than one class. But it sounds that I need to either go for dummy methods or abstract class. hmmm dummy methods would be more preferable to me than the abstract class :-(
By implementing one of the SOLID principle which is "Interface Segregation Principle" in which Interface is broken into mutiple interfaces.
Apart from the above excellent suggestions on designing interfaces, if you really need to have implementation of some of the methods,an option is to use 'Extension methods'. Move the methods that need implementation outside of your interface. Create another static class that implements these as static methods with the first parameter as 'this interfaceObject'. This is similar to extension methods used in LINQ for IEnumerable interface.
public static class myExtension {
public static void myMethod( this ImyInterface obj, ... ) { .. }
...
}

C# - using polymorphism in classes I didn't write

What is the best way to implement polymorphic behavior in classes that I can't modify? I currently have some code like:
if(obj is ClassA) {
// ...
} else if(obj is ClassB) {
// ...
} else if ...
The obvious answer is to add a virtual method to the base class, but unfortunately the code is in a different assembly and I can't modify it. Is there a better way to handle this than the ugly and slow code above?
Hmmm... seems more suited to Adapter.
public interface ITheInterfaceYouNeed
{
void DoWhatYouWant();
}
public class MyA : ITheInterfaceYouNeed
{
protected ClassA _actualA;
public MyA( ClassA actualA )
{
_actualA = actualA;
}
public void DoWhatYouWant()
{
_actualA.DoWhatADoes();
}
}
public class MyB : ITheInterfaceYouNeed
{
protected ClassB _actualB;
public MyB( ClassB actualB )
{
_actualB = actualB;
}
public void DoWhatYouWant()
{
_actualB.DoWhatBDoes();
}
}
Seems like a lot of code, but it will make the client code a lot closer to what you want. Plus it'll give you a chance to think about what interface you're actually using.
Check out the Visitor pattern. This lets you come close to adding virtual methods to a class without changing the class. You need to use an extension method with a dynamic cast if the base class you're working with doesn't have a Visit method. Here's some sample code:
public class Main
{
public static void Example()
{
Base a = new GirlChild();
var v = new Visitor();
a.Visit(v);
}
}
static class Ext
{
public static void Visit(this object b, Visitor v)
{
((dynamic)v).Visit((dynamic)b);
}
}
public class Visitor
{
public void Visit(Base b)
{
throw new NotImplementedException();
}
public void Visit(BoyChild b)
{
Console.WriteLine("It's a boy!");
}
public void Visit(GirlChild g)
{
Console.WriteLine("It's a girl!");
}
}
//Below this line are the classes you don't have to change.
public class Base
{
}
public class BoyChild : Base
{
}
public class GirlChild : Base
{
}
I would say that the standard approach here is to wrap the class you want to "inherit" as a protected instance variable and then emulate all the non-private members (method/properties/events/etc.) of the wrapped class in your container class. You can then mark this class and its appropiate members as virtual so that you can use standard polymorphism features with it.
Here's an example of what I mean. ClosedClass is the class contained in the assembly whose code to which you have no access.
public virtual class WrapperClass : IClosedClassInterface1, IClosedClassInterface2
{
protected ClosedClass object;
public ClosedClass()
{
object = new ClosedClass();
}
public void Method1()
{
object.Method1();
}
public void Method2()
{
object.Method2();
}
}
If whatever assembly you are referencing were designed well, then all the types/members that you might ever want to access would be marked appropiately (abstract, virtual, sealed), but indeed this is unfortunately not the case (sometimes you can even experienced this issue with the Base Class Library). In my opinion, the wrapper class is the way to go here. It does have its benefits (even when the class from which you want to derive is inheritable), namely removing/changing the modifier of methods you don't want the user of your class to have access to. The ReadOnlyCollection<T> in the BCL is a pretty good example of this.
Take a look at the Decorator pattern. Noldorin actually explained it without giving the name of the pattern.
Decorator is the way of extending behavior without inheriting. The only thing I would change in Noldorin's code is the fact that the constructor should receive an instance of the object you are decorating.
Extension methods provide an easy way to add additional method signatures to existing classes. This requires the 3.5 framework.
Create a static utility class and add something like this:
public static void DoSomething(this ClassA obj, int param1, string param2)
{
//do something
}
Add a reference to the utility class on the page, and this method will appear as a member of ClassA. You can overload existing methods or create new ones this way.

Categories

Resources