Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic wrapper class

Tags:

c#

c#-4.0

Given the following hierarchy:

class A
{
}
class B : A
{
    public void Foo() { }
}
class C : A
{
    public void Foo() { } 
}

This is a third-party library and I can't modify it. Is there a way I can write some kind of 'generic templated wrapper' which would forward the Foo() method to the apropriate object passed as constructor argument? I ended up writing the following, which uses no generics and seems rather ugly:

class Wrapper
    {
        A a;
        public Wrapper(A a)
        {
            this.a = a;
        }

        public void Foo()
        {
            if (a is B) { (a as B).Foo(); }
            if (a is C) { (a as C).Foo(); }
        }

    }

I'd love some template constraint like Wrapper<T> where T : B or C.

like image 391
amnezjak Avatar asked May 08 '13 10:05

amnezjak


People also ask

What is generic class with example?

A Generic class simply means that the items or functions in that class can be generalized with the parameter(example T) to specify that we can add any type as a parameter in place of T like Integer, Character, String, Double or any other user-defined type.

What are the 8 wrapper classes in Java?

Overview. As the name suggests, wrapper classes are objects encapsulating primitive Java types. Each Java primitive has a corresponding wrapper: boolean, byte, short, char, int, long, float, double.

What is generic class in OOP?

Generic classes encapsulate operations that are not specific to a particular data type. The most common use for generic classes is with collections like linked lists, hash tables, stacks, queues, trees, and so on.


1 Answers

If A does not have Foo, you need to either use dynamic (see Jon Skeet's answer) or use a little trick with lambdas and overloading:

class Wrapper {
    private Action foo;
    public Wrapper(B b) {
        foo = () => b.Foo();
    }
    public Wrapper(C c) {
        foo = () => c.Foo();
    }
    public void Foo() {
        foo();
    }
}

Now you can do this:

var wb = new Wrapper(new B());
wb.Foo(); // Call B's Foo()
var wc = new Wrapper(new C());
wc.Foo(); // Call C's Foo()

This shifts the decision on what method to call from the moment the Foo is called to the moment the Wrapper is created, potentially saving you some CPU cycles.

like image 172
Sergey Kalinichenko Avatar answered Sep 24 '22 08:09

Sergey Kalinichenko