Strange inheritance modification - c#

I'm a .NET developer and know pretty much about OOP.
However, recently I noticed one interesting fact.
System.Data.SqlClient.SqlCommand derives from
System.Data.Common.DbCommand. The latter implements System.IDbCommand.
System.IDbCommand exposes the property Connection which an instance of IDbConnection.
In DbCommand However this property returns DbConnection type. And finally the same property in SqlCommand is of type SqlConnection
I've tried to perform the same however it gave a compile time error. How was this achieved in above example and how can I recreate the same pattern?
My code (not compiling):
public interface IFoo { }
public interface IBar
{
IFoo TheFoo();
}
public abstract class AbsFoo : IFoo { }
public abstract class AbsBar : IBar
{
public abstract AbsFoo TheFoo();
}
public class ConcreteFoo : AbsFoo { }
public class ConcreteBar : AbsBar { }

Explicit interface implementation is the name of the game here. Try this:
public abstract class AbsBar : IBar {
IFoo IFoo.TheFoo() { return this.TheFoo(); }
public abstract AbsFoo TheFoo();
}
Here's a good guide on implicit vs. explicit implementation.

I have to say that I think Richard was a little hard done by - his answer is just as good as Jason's in that they both only answered half of the question. Put them both together and you have the full answer.
To make this work with IDbCommand, DbCommand & SqlCommand there has to be an explicit implementation of IDbCommand in DbCommand (Jason's answer) and public method shadowing in SqlCommand (Richard's answer).
I'll give the full "Foo/Bar" example.
Start with these interfaces:
public interface IFoo
{
IBar GetBar();
}
public interface IBar { }
Next Foo must provide an explicit implementation of IFoo in order to return Bar, not IBar, from its own GetBar method:
public abstract class Foo : IFoo
{
IBar IFoo.GetBar()
{
return this.GetBar();
}
public Bar GetBar()
{
return this.GetBarInner();
}
protected abstract Bar GetBarInner();
}
public abstract class Bar : IBar { }
And finally a SomeFoo class must shadow GetBar to be able to return a SomeFoo instance:
public class SomeFoo : Foo
{
public new SomeBar GetBar()
{
return new SomeBar();
}
protected override Bar GetBarInner()
{
return this.GetBar();
}
}
public class SomeBar : Bar { }
I think the only information that Richard is that my adding the new keyword to the shadowed method you get rid of the compiler error.

Connection in DbCommand and SqlCommand are both just public methods. There would be a compiler warning, but it's allowed. Your code should be more like this to work like SqlCommand/DbCommand:
public interface IFoo { }
public abstract class AbsBaseBar
{
public IFoo TheFoo() { throw new NotImplementedException(); }
}
public class AbsFoo : IFoo { }
public class AbsBar : AbsBaseBar
{
public AbsFoo TheFoo() { throw new NotImplementedException(); }
}
public class ConcreteFoo : AbsFoo { }
public class ConcreteBar : AbsBar { }

Related

Generic interfaces and inheritance to call a generic method

I want to have a generic class which could call a method based on its generic type which is defined by a derived class. For that I implemented a base interface and a generic interface which has the base interface as generic and also derives from the base interface.
In the generic interface I want a method based on the type T of the base interface.
After that I wanted to implement a class based on the generic interface which should be able to call the generic method. This is the example code:
public interface BaseInterface
{ }
public interface GenericInterface<T> : BaseInterface where T : BaseInterface
{
void Foo(T t);
}
public class C<T> : GenericInterface<T> where T : BaseInterface
{
public C()
{
// None of these works
Foo(this);
Foo((T)this);
Foo((BaseInterface)this);
}
public void Foo(T t) { }
}
Is there a way to achieve my desired behavior here?
The error message here is:
cannot convert from 'C<T>' to 'T'
which in my eyes should be possible because C derives from BaseInterface which is T
While both C<T> and T need to derive from BaseInterface, that does not mean that then need to be the same. I might for example declare another type B : BaseInterface, and C<B>. So we would get the method Foo(B t) , it would obviously not be possible to call the method with this as the parameter, since C<B> is not B.
If you just need a method that needs a BaseInterface parameter, just declare it as Foo(BaseInterface t) instead. That way you could call it with this without any problem.
It looks like you're looking for something like the Curiously Recurring Template Pattern for C#. In a simplified form it looks like this:
class Base<T>
{
public void Foo(T t) { }
}
class C : Base<C>
{
C()
{
Foo(this);
}
}
In your case T is a type that derives from BaseInterface. Although C<T> also derives from BaseInterface it doesn't mean that you can bind a C<T> to T t. It's like trying to bind a string to a List, just because both implement IEnumerable. They are still different types.
For your full example it could look like this
public interface BaseInterface
{ }
public interface GenericInterface<T> : BaseInterface where T : BaseInterface
{
void Foo(T t);
}
public class C<T> : GenericInterface<C<T>> where T : BaseInterface
{
public C()
{
Foo(this);
}
public void Foo(C<T> t) { }
}
Here's what you need for the Curiously Recurring Template in C#.
public interface BaseInterface { }
public interface GenericInterface<T> : BaseInterface where T : GenericInterface<T>
{
void Foo(T t);
}
public abstract class C<T> : GenericInterface<T> where T : C<T>
{
public abstract void Foo(T t);
}
Now you can go ahead and implement a real class:
public class D : C<D>
{
public D()
{
Foo(this);
Foo((D)this);
}
public override void Foo(D t) { }
}
That works fine.
However, calling Foo((BaseInterface)this); will never work in this code. It just doesn't make sense.
I Tried this, maybe can help you
public class C<T> : GenericInterface<T> where T : BaseInterface
{
public C()
{
T t = default(T);
BaseInterface bi;
bi = t; // here can cast , bacuse T : BaseInterface , not BaseInterface : T
t = bi;//here cast error ,
}
public void Foo(T t) { }
}
It's same like this case:
public class B { }
public class A : B
{
public void CastTest()
{
A a = null;
B b = null;
b = a;
a = b;//here error
}
}

Interface and abstract c# inheritance

I am encountering a problem with interfaces. I wish to chain a method which derives its chainable method from an abstract class, which implements an interface.
public interface IBaseInterface {
public IBaseInterface ChainableMethod()
}
public abstract AbstractClassThatHelps<T> where T: IBaseInterface n {
public T ChainableMethod() {
return (T) this;
}
}
public interface IDerived : IBaseInterface { }
public class DerivedClass : AbstractClassThatHelps<IDerived>, IDerived { }
IDerived derived = new DerivedClass();
derived.ChainableMethod().ChainableMethod();
The problem I face here: why can't T be returned when it is shown to implement the contract IModel?
How would I solve this differently? I wish to have type safety but I am forced for all derived classes to return IBaseInterface instead of their own interface.
Actual implementation:
We have multiple models (DerivedClass's) which implement their respective IDerived for dependency injection. These need helpers because i dont want to repeat myself.. So we use AbstractClassThatHelps as a base, but because we are dealing with chainable methods we need this base class to know what to return, so therefore generics. IBaseInterface can be seen as IModel. Where ChainableMethod can be seen as GetAll() for example.
In order for the following code to work AbstractClassThatHelps<T> must implement IBaseInterface. How can you return this, if this is not IBaseInterface
public abstract AbstractClassThatHelps<T> where T: IBaseInterface n{
public T ChainableMethod(){
return this;
}
}
Edit: I am not user what this design solves but here is my attempt at what you are trying to achieve→
public interface IBaseInterface
{
IBaseInterface ChainableMethod();
}
public abstract class AbstractClassThatHelps<T>:IBaseInterface where T : IBaseInterface{
public T ChainableMethod()
{
IBaseInterface i = this;
return (T)i.ChainableMethod();
}
IBaseInterface IBaseInterface.ChainableMethod()
{
return this;
}
}
public class Concrete : AbstractClassThatHelps<Concrete>
{
}
You can return an instance of T, but the return type cannot be T but must be IBaseInterface because that is what the interface requires.
This is working, your code was full of syntax errors:
public interface IBaseInterface
{
IBaseInterface ChainableMethod();
}
public abstract class AbstractClassThatHelps : IBaseInterface
{
public IBaseInterface ChainableMethod()
{
return this;
}
}
public interface IDerived : IBaseInterface
{
}
public class DerivedClass : AbstractClassThatHelps, IDerived
{
}
internal static class Program
{
public static void Main()
{
IDerived derived = new DerivedClass();
derived.ChainableMethod().ChainableMethod();
}
}
you could also try this:
public interface IBaseInterface
{
IBaseInterface ChainableMethod();
}
public abstract class AbstractClassThatHelps<T> : IBaseInterface where T : class, IBaseInterface
{
public T ChainableMethod()
{
return this as T;
}
IBaseInterface IBaseInterface.ChainableMethod()
{
return ChainableMethod();
}
}
public interface IDerived : IBaseInterface
{
IDerived Hello();
}
public class DerivedClass : AbstractClassThatHelps<IDerived>, IDerived
{
public IDerived Hello()
{
Console.WriteLine("Hello");
return this;
}
}
internal static class Program
{
public static void Main()
{
AbstractClassThatHelps<IDerived> derived = new DerivedClass();
derived.ChainableMethod().Hello().ChainableMethod();
}
}

Return a subclass of abstract return type?

My project is structured the following way:
// Abstract class
public abstract class Job
{
public abstract JobResult Run();
}
public abstract class JobResult { }
// Concrete implementer
public class Job1 : Job
{
public override Job1Result Run() { }
}
public class Job1Result : JobResult { }
Each concrete job inherits from Job and implements the method Run which returns a concrete class of JobResult.
However when I do this I get the compiler error:
Job1.Run()': return type must be JobResult to match overridden member
Job.Run()
Is it really not possible to return an inheriting object of the return type when overriding an abstract method?
This is the whole concept of inheritance. Returning parent classes is considered a feature here. Nothing stops you however from returning a Job1Result in Job1
public JobResult Run()
{
return new Job1Result();
}
Then the caller of Job1.Run() will have to know the correct return type and cast it to access Job1Result methods which are specific to that class
You could make Job generic:
public abstract class Job<TResult> where TResult : JobResult
{
public abstract TResult Run();
}
public class Job1 : Job<Job1Result>
{
public override Job1Result Run()
{
//
}
}
Here is an example, I hope it can help you.
public interface IEvent
{
Type GetEventType();
}
public abstract class AEvent<A>: IEvent where A: struct
{
public Type GetEventType()
{
return typeof (A); // return sub struct type
}
}

Proxy exposing multiple interfaces with Ninject.Extensions.Interception.Linfu

I'm using Ninject.Extensions.Interception (more specifically, InterceptAttribute) and Ninject.Extensions.Interception.Linfu proxying to implement a logging mechanism in my C# app, but I am facing some problems when a proxied class implements several interfaces.
I've a class which implements an interface and inherits from an abstract class.
public class MyClass : AbstractClass, IMyClass {
public string SomeProperty { get; set; }
}
public class LoggableAttribute : InterceptAttribute { ... }
public interface IMyClass {
public string SomeProperty { get; set; }
}
public abstract class AbstractClass {
[Loggable]
public virtual void SomeMethod(){ ... }
}
When I try to get an instance of MyClass from ServiceLocator, the Loggable attribute causes it to return a proxy.
var proxy = _serviceLocator.GetInstance<IMyClass>();
The problem is the proxy returned only recognizes the AbstractClass interface, exposing SomeMethod(). Consequentially, I receive an ArgumentException when I try to access the inexistent SomeProperty.
//ArgumentException
proxy.SomeProperty = "Hi";
In this case, is there a way of using mixin or some other technique to create a proxy exposing multiple interfaces?
Thanks
Paulo
I ran in a similar problem and i did not found a elegant solution with only ninject means. So i tackled the problem with a more basic pattern from OOP: composition.
Applied to your problem something like this would be my suggestion:
public interface IInterceptedMethods
{
void MethodA();
}
public interface IMyClass
{
void MethodA();
void MethodB();
}
public class MyInterceptedMethods : IInterceptedMethods
{
[Loggable]
public virtual void MethodA()
{
//Do stuff
}
}
public class MyClass : IMyClass
{
private IInterceptedMethods _IInterceptedMethods;
public MyClass(IInterceptedMethods InterceptedMethods)
{
this._IInterceptedMethods = InterceptedMethods;
}
public MethodA()
{
this._IInterceptedMethods.MethodA();
}
public Method()
{
//Do stuff, but don't get intercepted
}
}

Explicitly implementing an interface with an abstract method

Here is my interface:
public interface MyInterface {
bool Foo();
}
Here is my abstract class:
public abstract class MyAbstractClass : MyInterface {
abstract bool MyInterface.Foo();
}
This is the compiler error:
"The modifier 'abstract' is not valid for this item.
How should I go on about explicitly implementing an abstract with an abstract method?
You can't, basically. Not directly, anyway. You can't override a method which is explicitly implementing an interface, and you have to override an abstract method. The closest you could come would be:
bool MyInterface.Foo() {
return FooImpl();
}
protected abstract bool FooImpl();
That still implements the interface explicitly and forces derived classes to actually provide the implementation. Are those the aspects you're trying to achieve?
You have to use an implicit implementation of the interface member instead of an explicit implementation:
public abstract class MyAbstractClass : MyInterface
{
public abstract bool Foo();
}
In fact there is another option than using an abstract helper method which still keeps the implementation private:
public abstract class MyAbstractClass : MyInterface
{
bool MyInterface.Foo() // must be overridden
{ throw NotImplementedException(); // never called
}
}
public class MyDerivedClass : MyAbstractClass, MyInterface
{
bool MyInterface.Foo() // overrides MyInterface.Foo
{ // Place your implementation here
}
}
This pattern will also work if the interface has many methods and only some of them are redefined in the derived class. And, of course, you can also use this to override private interface implementations in general.
The major disadvantage is that Foo cannot be declared abstract in MyAbstractClass, so the compiler cannot ensure that the method is actually overridden. (It's a pity that abstract classes may not have incomplete interface implementations in C#.)
The advantage is that you save one calli instruction that is likely to cause CPU pipeline stalls. However, the impact is quite small, since the method cannot be inlined anyway because of the interface call. So I would recommend it only for performance critical cases.
I'm not sure why you need to. Why not let the concrete implementation of the abstract class implement the member from the interface? It's the same thing really.
An abstract method has no implementation, so it can't be used to explicitly implement an interface method.
I am able to do this
public interface SampleInterface
{
void member1();
void member2();
void member3();
}
public abstract class Client2 : SampleInterface.SampleInterface
{
public void member1()
{
throw new NotImplementedException();
}
public abstract void member2();
public void member3()
{
throw new NotImplementedException();
}
}
public class Client3 : Client2
{
public Client3()
{
}
public override void member2()
{
throw new NotImplementedException();
}
}
In addition to Jon's explanation: this is a way to bypass the problem instead of solving it directly and will work only in certain circumstances, but maybe someone will benefit from this idea.
If you plan to pass all (or at lest most) interface method calls to the derived class, you can do it in the following way:
public interface MyInterface
{
bool Foo();
}
public abstract class MyAbstractClass
{
public abstract MyInterface AsMyInterface();
}
public class MyDerivedClass : MyInterface
{
public override MyInterface AsMyInterface()
{
return this;
}
public bool Foo()
{
return false;
}
}
...
MyAbstractClass c = new MyDerivedClass();
MyInterface i = c.AsMyInterface();
bool b = i.Foo();
Abstract all the interface methods that are implemented in a abstract class, even if you do not use them.
This particular case requires that you are implementing a hierarchy of 2 or more abstract classes, with a interface.
I was trying to implement a hierarchy in C# as well. I needed a Interface but I wanted a Abstract class, because most of the properties are the same for the interface. To do this I had to create a separate Abstract class, with the implementation, and then my Concrete classes, or in my case another abstract class, would inherit the Interface and the Abstract Class.
I do not think that this first one is a good example for many reasons, but I had to have it because the compiler would not allow FooBar to implement Foo and then have another abstract class to inherit FooBar. So I had a abstract class with a abstract method bar(), and the interface with the bar() method.
public interface Foo {
bool bar();
//other stuffs
}
public abstract class FooBar {
public abstract bool bar();
//Other stuffs
}
public abstract class FooBarAbstraction: FooBar, Foo {
//other stuffs
//Don't supply the interface and abstract here
}
public class FooBarConcrete: FooBarAbstraction {
public override bool bar() {
return true;
}
//other stuffs
}
This was my first attempt, then I got curious and started to think about it. I came across this solution. The better solution.
public interface Foo {
bool bar();
bool buzz();
//other stuffs
}
public abstract class FooBar : Foo{
public abstract bool bar();
public abstract bool buzz();
//Other stuffs
}
public abstract class FooBarAbstraction: FooBar {
//other stuffs
//Don't supply the interface and abstract here
// override everything else
public override bool buzz() {
return false;
}
}
public class FooBarConcrete: FooBarAbstraction {
public override bool bar() {
return true;
}
//other stuffs
}

Categories

Resources