c#: question about interfaces (is / as implimentation) - c#

I am going through headfirst c# and on a section about interfaces and I got to a bit i don't understand:
if (bees[i] is INectarCollector) {
INectarCollector thisCollector;
thisCollector = bees[i] as INectorCollector;
thisCollector.GatherNectar();
}
}
now I understand that you use interfaces so that you can pass different class objects into a method and such, and you use a interface reference to call interface methods.
Since the class implements the methods/properties couldn't I just call the implementation inside the field instead of using the reference?

Related

What's a difference between abstract base class and new C# interfaces with default methods [duplicate]

This question already has answers here:
Default Interface Methods. What is deep meaningful difference now, between abstract class and interface?
(6 answers)
The difference between abstract classes and interfaces in C# 8 release? [closed]
(3 answers)
What is the difference between an interface with default implementation and abstract class? [duplicate]
(1 answer)
Closed 2 years ago.
With the recent release of C# 8.0 (new feature mentioned here), it allows for providing default method implementation.
While I understand the reason why it's done, I wonder if there is any difference between these 2 concepts?
Thoughts?
To call default interface method You need to cast instance to the interface containing default implementation
You can implement multiple interfaces and cannot inherit multiple abstract classes
It is better to use abstract class for base functionality (provides better inheritance tree logic). And use interfaces with default method implementations to provide small side changes only when this default logic suits for most of implementations (like Microsoft did with their Collection methods).
Also try to not overuse default interface implementations, because this complicates behavior inheritance (you need to search interfaces too, not only classes) from linear to tree.
C++ allows multiple inheritance and without control this aspect can easily make the code unmaintainable.
These are the main differences I see:
Multiple Inheritance
Unlike other languages (like C++), C# does not allow a class to inherit directly from more that one class. On the other hand, a class can implement any number of interfaces, so the new default implementation feature allows you to do something similar to multi-inheritance.
Calling the Default Implementation
If you derive from a class and override a virtual method, you may use the base keyword to call the original implementation. Example:
public abstract class Base
{
public virtual void DoSomething()
{
...
}
}
public class Derived : Base
{
public override void DoSomething()
{
base.DoSomething(); //Here
...
}
}
Constructors and Non-Virtual Members
Abstract classes can declare constructors that the derived class will call. Also, an abstract class can contain non-virtual methods, while an interface can only have overridable (virtual) methods.

.NET COM Interop why can't we implement class inheritance like AutoDual

Is there a way to retain the class inheritance in c# while at the same time obeying the interface inheritance rules of COM interop? Or in a different sense, how can one duplicate the functionality of AutoDual with explicit interfaces?
I've received an API library written in C# from another company that uses Microsoft.Runtime.InteropServices. I am using it to compile to a DLL which our legacy software (in powerbuilder) uses to call the API. I'm trying to use ClassInterfaceType.None to avoid ClassInterfaceType.AutoDual which may break the functionality in the future. I am running into the following issue:
The company who wrote the API library used good Object Oriented design. While this reduces redundancy in the c# code, it works against my purposes because of the class inheritance structure going against COM interface requirements. E.g. the Get methods for each request (there are many) call the same method which expects an inherited generic type:
Generic Method:
private T Get<T>(string Foo, string Bar) where T : UmbrellaResponse, new() { /* get the response*/ }
Two of many specific methods:
namespace SeparateFromTheObjects
{
public SpecificResponse1 GetSpecificResponse1(string token)
{
return Get<SpecificResponse1>(token, "specific_thing");
}
public SpecificResponse2 GetSpecificResponse2(string token)
{
return Get<SpecificResponse2>(token, "specific_thing");
}
}
Which currently inherits like this:
public class SpecificResponse : UmbrellaResponse
So if I create an interface with all needed properties/methods and change it to SpecificResponse : ISpecificResponse or even : IUmbrellaResponse, all the methods can't be used because they no longer inherit from the CLASS UmbrellaResponse.
Basically, is there a way to retain the class inheritance in c# while at the same time obeying the interface inheritance rules of COM interop? Or in a different sense, how can one duplicate the functionality of AutoDual with explicit interfaces?
If impossible, how can you write methods (such as the get method above) to accommodate multiple objects that do not inherit from the same type?
I have read the following, but do not believe it contains an answer:
Why should I not use AutoDual?

C# Pattern for aggregating interface methods into one generic method

I'm searching for a pattern to aggregate interface methods into one generic method.
Better to make an example of what I'm trying to do
Consider that I have an interface with more then 40 methods which have all different responsibilities but the implementations of these methods are equal besides of function name an parameters.
interface MultiMethod{
public TypeA A (p1,p2);
public TypeA B (p1);
public TypeC C (p5,p3,p2);
.
.
.
}
Implementation Class
class MultiMethodeService : MultiMethod
In the MultiMethodeService I need to Implement all Interface methods, but the implementation of the methods is not real different.
Like:
public TypeA A (p1,p2){
proxy.call("remoteA").params(p1,p2);
}
public TypeB B (p1){
proxy.call("remoteB").params(p1);
}
I want to replace the implementation of the methods with one generic method that uses reflection.
The generic method derives
the parameters form the MultiMethod interface
the method name from the MultiMethode interface to invoke the equal proxy call
For me it is clear how implement the generic method, but how is it possible, when I have a generic method to also have the equal semantic like without a generic implementation.Deeper meaning code complition (intellisense) should work for the generic implementation equal to the OOP implementation.
When I afterwords want to use the service object of MultiMethodService like :
var service = new MultiMethodService()
service.A(p1,p2)
Some naive idea was to implement an enum{"A","B"}
service.callGeneric(enum.A, p1,p2);
service.callGeneric(enum.B, p1);
which is not really nice.
Again why would you implement this an not the straight forward OOP solution?
Prevent implementing the same method again and again with only a few changes that could be deduced by reflection from an interface
DRY, Don't reaped yourself. If the interface changes or parameter types, only refactor these but not the whole remote calls (interface implementation)
If you could provide any pattern or idea, your help is highly appreciated.
offtopic
More explanation needed? Lets say I have this javascript (typescript) interface in c# which represents the typescript service to c#. Additionally I have the c# classes reflecting the javascript classes. Now I have an mechanism to call from C# into javascript to compute the result. see here. Which is implemented in the interface methods. This repeats 46 times, and if something changes I have to refactor some of the implementation. How can I prevent reimplementing the inteface methods by using something generic. With the possibility to use afterwords the service like service.getSyntacticDiagnostics(...), I can rephrase this with, code completion(intellisense) should work equally to OOP style code.

Difference between abstract Class and Interface in C# [duplicate]

This question already has answers here:
Interface vs Base class
(38 answers)
Interface or abstract class?
(15 answers)
Closed 7 years ago.
this article says
Codeproject
Abstract Class -can have method Declaration and method definition.
But this article says
programcall
Abstract - can have only method Declaration.
I got confused. Can anybody clear me what is the exact difference of both ?
See this article:
Multiple inheritance
A class may inherit several interfaces.
A class may inherit only one abstract class.
Default implementation
An interface cannot provide any code, just the signature.
An abstract class can provide complete, default code and/or just the details that have to be overridden.
Access Modfiers
An interface cannot have access modifiers for the subs, functions, properties etc everything is assumed as public An abstract class can contain access modifiers for the subs, functions, properties
Core VS Peripheral
Interfaces are used to define the peripheral abilities of a class. In other words both Human and Vehicle can inherit from a IMovable interface.
An abstract class defines the core identity of a class and there it is used for objects of the same type.
Homogeneity
If various implementations only share method signatures then it is better to use Interfaces.
If various implementations are of the same kind and use common behaviour or status then abstract class is better to use.
Adding functionality (Versioning)
If we add a new method to an Interface then we have to track down all the implementations of the interface and define implementation for the new method.
If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly.
Fields and Constants No fields can be defined in interfaces An abstract class can have fields and constrants defined
As far as I know, abstract classes can already implement some methods or variable's values, as long as it does not implement them all (which would make it a normal class).
An interface cannot do this; it can only provide method and variable stubs.
An interface is more of a contract - it details what methods or properties will be found on an object that implements it.
An abstract class is a base object - it can contain methods, variables and behaviour - however you cannot create a concrete implementation of it - you must inherit from it and extend its behaviour.

ActionScript3 interface implementation without public accessor?

In C#, it's possible implementing interface methods without making implementing method as public. For example,
void ITest.SomeMethod()
{
// ...
}
Is there equivalent for ActionScript3?
Nope. From the AS3 Language Spec:
Classes that implement an interface method must use the public attribute to implement all interface methods.
In ActionScript, there is no way to add access level qualifiers; however, this question has been asked here, leveraging inheritance of interfaces:
How to expose a method in an interface without making it public to all classes
Perhaps an internal class may be another approach; although, not recommended.
But directly no, all members of ActionScript interfaces are public.

Categories