Class vs Interface - c#

Recently I was asked in an interview that, can an Interface be considered as a class in C#? I.e. is an interface is a class in C#?
I was confused.
What can be the answer?

No, an interface is not a class.
An interface is a set of method signatures and possibly properties that all relate to a single idea. For example, the IList interface will have methods for indexing, inserting, and getting the number of elements. However, it does not define any implementation details. The list interface could be implemented as a linked list, or a wrapped up array, or anything you want, as long as it defines those methods in the interface.
A class is the template from which to create an actual object. Classes are a collection of method signatures, plus the implementations of those methods.
So no, an interface is not a class, as it merely defines a specific contract, while a class defines the whole behaviour of the object.
Commenter SquareCog accurately points out that the above is not entirely true. Since classes can be subclassed, and methods overridden, the class' relationship to the actual behaviour of an object gets somewhat more complicated. I'm just going to handwave that problem away by saying that classes are individual entities. You can read the source code for a class and know what behaviour that class encompasses. However, at runtime, objects have types instead of classes. Types are the entire inheritance tree, instead of a singular class, and thus a type's behaviour could be defined over several different classes. Luckily, this does not change the basic conceptual difference that interfaces are contracts that can imply (through names, argument types, etc) certain implementations, but cannot enforce anything but the method signatures, while classes do define an implementation, even if that is not the actual implementation used at runtime.

From a logical perspective, they are very similar. As noted by others, an ABC1 with only public abstract members would serve almost the same purpose as an interface.
When you get down to the nuts and bolts of it, the two have a number of important differences.
A class can only inherit from one base classes, but can implement many interfaces.
A value type, already deriving from ValueType, cannot inherit from an ABC, but can implement an interface.
A class can contain fields and static members. An interface cannot.
A class can contain implementation, an interface cannot.
A class can have private and protected members, an interface cannot.
Abstract members of an ABC are always virtual. A class can implement an interface with non-virtual members.
1: Abstract Base Class

Yes, any abstract class that contains no implementation and consists of abstract methods only would be equivalent to interface.

A Java interface is not a class; it is a declaration of methods that need to be implemented by classes; a description of abilities, if you will. Abstract classes in Java are an interesting half-way point between proper classes and interfaces, as they define the available methods, but also provide some default implementations.
The fundamental difference between an abstract class and an interface in Java is that you can only extend one class; you can implement multiple interfaces. An abstract class describes what you are; an interface describes what you can do. What you are also defines what you can do -- but it has significantly stronger meaning.

In general, an Interface is a type that can be implemented by a class to indicate that the class exposes a behavior through a set of methods. For example, .Net has an ICollection interface that contains methods to interact with a collection.
In C++, an interface is a class where every method is abstract.
In Java and .Net, interfaces are independent types that are unrelated to classes.
Either way, classes can implement interfaces.

There could be several answers.
No, a class is not an interface - an interface defines a contract, a class is a type of object which can be created.
Yes, an interface can be viewed as a base class with only virtual methods - this is how interfaces are defined in C++.

It's helpful to regard .net as having three "safe" kinds of types in .net: interfaces, classes, and value-types (there are also things like pointers and such, but those are another story), and three main contexts classes may be used: storage locations, heap objects, and generic constraints.
Heap objects may be of any type, but all heap objects behave like class objects. Heap objects of interface type are rare; they are not generally created within .net but may be created by code designed to work with older object models. Heap objects of class types contain one storage location for each field; heap objects of value types contain one storage location whose type is the value type in question.
Storage locations may likewise be of any type, but value-type storage locations differ from the others. A storage location of class type or interface type holds a class reference. A value-type storage location contains either a value primitive (byte, integer, char, floating-point number, etc.) or else contains a storage location for each field of the value type (so, e.g., a storage location of type Point holds two storage locations of type Int32, each of which holds a signed-32-bit-integer primitive).
Generic constraints may also be of any type, but constraints of interface types do not confine the constrained generic type parameter itself as being a class type, interface type, or value type. A method declared void Foo<T>(T param) where T:IWowzo could be called with a parameter of class type, interface type, or value type. If the routine is called with a value-type parameter, then param and any other storage locations declared to be of type T will be stored as value types. If the routine is called with a parameter of class type or integer type, then param and any other storage locations declared to be of type T will be stored as class references. It's important to note that if T is itself an interface type (IWozo or a derivative) then param will be passed as a reference to a heap object, and will behave like one regardless of whether the type of the object instance is a class object or value type. If struct Bar implements IWowzo, and myBar is a variable of type Bar, calling Foo<Bar>(myBar) may yield different semantics from Foo<IWowzo>(myBar); in the former case, the parameter will behave as a value type and in the latter case it will behave as a class type.

Related

Generic Interface class signature

I get inheritance, I just don't get why this interface implements itself?
Also, please could you explain what the emboldened part does? Why can I not just say where T is IIdentifiableEntity, instead of all those comma separated sections?
public interface IDataRepository<T> : IDataRepository
**where T : class, IIdentifiableEntity, new()**
Theres more than one question here.. I'll tackle them one by one:
Why this interface implements itself?
It doesn't. There is two types here .. one generic .. one non-generic. Why does it implement the non-generic one? Who knows .. we need to see the entire data layer to understand that. Its important to realize they are two types though.
Why can I not just say where T is IIdentifiableEntity
Again, this depends on your use case. class enforces a reference type as the generic parameter. So, you will not be able to create an instance of IDataRepository<int>. This makes sense in a data layer.. as you generally want to persist entire objects/graphs and they are generally reference types. new() allows you to use var x = new T() in your generic type. Without it, you will get a compiler error if you try to instantiate an instance of your generic type parameter.
It is often useful to define interfaces either for generic collection classes, or for the generic classes that represent items in the collection. The preference for generic classes is to use generic interfaces, such as IComparable rather than IComparable, in order to avoid boxing and unboxing operations on value types. The .NET Framework class library defines several generic interfaces for use with the collection classes in the System.Collections.Generic namespace.
When an interface is specified as a constraint on a type parameter, only types that implement the interface can be used. The following code example shows a SortedList class that derives from the GenericList class. For more information, see Introduction to Generics (C# Programming Guide). SortedList adds the constraint where T : IComparable. This enables the BubbleSort method in SortedList to use the generic CompareTo method on list elements. In this example, list elements are a simple class, Person, that implements IComparable. Read
There are 2 different interface IDataRepository which is general and IDataRepository<T> which is generic and restricted to class which has parameter less constructor and implemented IIdentifiableEntity. This is useful when your application is not only tied to IDataRepository<T> but you might have another generic interface likeIDataRepository<T> where T: IEntity, and in some parts you want to treat them as one interface
For the next question if it only has where T : IIdentifiableEntity you can pass another interface or struct as T , but the architect wants developers to pass a class which has a parameter constructor as T

Is this a type of polymorphism in object-oriented programming?

static void Main(string[] args)
{
string str = "abc";
str += "xyz";
Console.WriteLine(str);
}
Here is += a type of polymorphism?
No, its not polymorphism its string concatenation
Polymorphism (C# Programming Guide) (base-derived class based)
Polymorphism is often referred to as the third pillar of
object-oriented programming, after encapsulation and inheritance.
Polymorphism is a Greek word that means "many-shaped" and it has two
distinct aspects:
At run time, objects of a derived class may be treated as objects of a base class in places such as method parameters and collections or
arrays. When this occurs, the object's declared type is no longer
identical to its run-time type.
Base classes may define and implement virtual methods, and derived classes can override them, which means they provide their own
definition and implementation. At run-time, when client code calls the
method, the CLR looks up the run-time type of the object, and invokes
that override of the virtual method. Thus in your source code you can
call a method on a base class, and cause a derived class's version of
the method to be executed.
Edit, There are different types of Polymorphism as mentioned in this MSDN article.
Interface polymorphism - Multiple classes may implement the same interface, and a single class may implement one or more interfaces.
Interfaces are essentially definitions of how a class needs to
respond. An interface describes the methods, properties, and events
that a class needs to implement, and the type of parameters each
member needs to receive and return, but leaves the specific
implementation of these members up to the implementing class.
Inheritance polymorphism - Multiple classes may inherit from a single base class. By inheriting, a class receives all of the methods,
properties, and events of the base class in the same implementation as
the base class. Additional members can then be implemented as needed,
and base members can be overridden to provide different
implementations. Note that an inherited class may also implement
interfaces — the techniques are not mutually exclusive.
Polymorphism through abstract classes - Abstract classes provide elements of both inheritance and interfaces. An abstract class is a
class that cannot be instantiated itself; it must be inherited. Some
or all members of the class might be unimplemented, and it is up to
the inheriting class to provide that implementation. Members that are
implemented might still be overridden, and the inheriting class can
still implement addition interfaces or other functionality.
a += b naturally means a = a + b. In the case of strings, the + operator concatenates the second string onto the first. It's not an overloaded function (which I suspect is what you mean), but rather an overloaded operator, which by definition is a specific kind of polymorphism. So the simple answer is yes, but perhaps not in the way you think.
This is Operator Overloading, not Polymorphism, which in this case does string concatenation.
You can find more information on Operator Overloading at this location: MSDN Link to Operator Overloading

Empty interfaces and abstract class enforce structure

I've been looking into empty interfaces and abstract classes and from what I have read, they are generally bad practice. I intend to use them as the foundation for a small search application that I am writing. I would write the initial search provider and others would be allowed to create their own providers as well. My code's intent is enforce relationships between the classes for anyone who would like to implement them.
Can someone chime in and describe if and why this is still a bad practice and what, if any alternatives are available.
namespace Api.SearchProviders
{
public abstract class ListingSeachResult
{
public abstract string GetResultsAsJSON();
}
public abstract class SearchParameters
{
}
public interface IListingSearchProvider
{
ListingSeachResult SearchListings(SearchParameters p);
}
}
Empty classes and interfaces are generally only "usably useful" as generic constraints; the types are not usable by themselves, and generic constraints are generally the only context in which one may use them in conjunction with something else useful. For example, if IMagicThing encapsulates some values, some implementations are mutable, and some aren't, a method which wants to record the values associated with an IMagicThing might be written something like:
void RecordValues<T>(T it) where T:IImagicThing,IIsImmutable {...}
where IIsImmutable is an empty interface whose contract says that any class which implements it and reports some value for any property must forevermore report the same value for that property. A method written as indicated could know that its parameter was contractually obligated to behave as an immutable implementation of IMagicThing.
Conceptually, if various implementations of an interface will make different promises regarding their behaviors, being able to combine those promises with constraints would seem helpful. Unfortunately, there's a rather nasty limitation with this approach: it won't be possible to pass an object to the above method unless one knows a particular type which satisfies all of the constraints, and from which object derives. If there were only one constraint, one could cast the object to that type, but that won't work if there are two or more.
Because of the above difficulty when using constrained generics, it's better to express the concept of "an IMagicThing which promises to be immutable" by defining an interface IImmutableMagicThing which derives from IMagicThing but adds no new members. A method which expects an IImmutableMagicThing won't accept any IMagicThing that doesn't implement the immutable interface, even if it happens to be immutable, but if one has a reference to an IMagicThing that happens to implement IImmutableMagicThing, one can cast that reference to the latter type and pass it to a routine that requires it.
Incidentally, there's one other usage I can see for an empty class type: as an identity token. A class need not have any members to serve as a dictionary key, a monitor lock, or the target of a weak reference. Especially if one has extension methods associated with such usage, defining an empty class for such purpose may be much more convenient than using Object.

How can a value type implement a ref type

I came across a scenerio where a value type is implementing ref. type.
Just want to know how come is that possible ( what goes behind the scene ?)
A struct is a value type and interface a ref. type but a struct can implement interface without any error...
Any thoughts?
Thanks in advance
Actually, it does it in two different ways at once.
Firstly, any value-type can be boxed into a reference-typed object instance. This box is invented by the runtime on demand and will implement the interface in the way you expect - i.e. the box will implement any interfaces the value-type implements.
However, the CLI also allows for a "constrained call". A constrained call turns a virtual call into a static call but only in exactly to the scenario where a value type implements an instance method by way of override or interface implementation (otherwise it is implemented by the JIT as a virtual call). In particular generics makes extensive use of constrained calls (the constrained opcode was added at the same time as generics, for exactly this reason).
An interface is not a reference type, it's just a contract for how to implement a type.
A variable of an interface type has to be a reference though, as a type that implements the interface can be a reference type. A variable of an interface type has to be able to hold either a reference type or a value type, as both can implement the interface. A value type can be boxed so that it gets a reference, but a reference type can't be "flattened" into a value.
Although we all use the word Type to refer to interfaces, and indeed, even the MSDN documentation describes interfaces as reference Types, an interface is not a Type in the same sense as any other reference type or any value type. It is, in a very real sense not a type at all. It is a contract for a behavior (a set of methods, properties, and events) that a type must contain by having been declared to implement that interface.
public interface ITestInterface { }
public class MyClass:ITestInterface { }
ITestInterface m = new MyClass() as ITestInterface;
var t = m.GetType();
You will see that even though variable m is declared to be of type ITestInterface, the Type variable t is still MyClass.
So, even though, for historical reasons we use the word type to apply to interfaces, the "type" of an interface is a very different thing that the type of a concrete object, which is an instance of a class or struct.
to quote from Don Box's Essential .Net
The CLR deals with objects and interfaces types differently than its
predecessors (C++ and COM). In C++ and COM, a given concrete type
has one method table per base type or supported interface. In
contrast, a given concrete type in the CLR has exactly one method
table. By inference, a CLR-based object has exactly one type handle.
This is in stark contrast to C++ and COM, where an object would
routinely have one vptr per base type or interface. For this reason,
the CLR's castclass does not result in a second pointer value in the
same way as C++'s dynamic_cast or COM's Query-Interface.
Reading this it is clear that an interface, itself, can never have a vptr table, or a CORINFO_CLASS_STRUCT as only true concrete objects (reference and value types) can have. This structure is created and maintained by the CLR for each Type that is loaded by the executing code at runtime. Again, from Essential .Net,
The CORINFO_CLASS_STRUCT contains pointers to two tables that describe
all interfaces the type supports. The isinst and castclass [CLR]
opcodes use one of these tables to determine whether a type supports a
given interface. The second of these tables is an interface offset
table that the CLR uses when dispatching virtual method calls made
against interface-based object references.
As can be seen clearly from these references, an interface is a fundamentally different kind of thing than a reference type (a class), or a value type (a struct). Every object (reference type) or value type instantiated or used within .Net must be a concrete instance of either a class, or a struct. And every object or struct loaded by the CLR has a reference to the single CORINFO_CLASS_STRUCT created for the concrete type of that class or struct. Intefaces are categories of types, defined so as to guarantee that any class or struct declared to be in that category (declared to implement that interface), must contain a type member (method, property, event, etc.) for each member declared in the interface definition.
Interfaces are not types in a sense that classes and structs are! Interfaces do not exist by themselves; so they are neither reference type nor value type. You can assign null to a reference. But if the implementer type is a value type, when you assign a variable of that type to another type, it behaves like a value type. And so it behave like a reference type for reference types.
Classes and structs are types for data(code) but interfaces are types for types. They can be used for categorizing other types. They force other types to follow a protocol and nothing more. They are just a layout, a definition, a contract; not an existing thing.

How is polymorphysm look like by using Interfaces?

I don't get the connection of Interfaces To polymorphism.
Polymorphism for me is about executing a method in a different way for some different concrete classes using abstract methods or virtual methods+ overriding and therefore this is only linked to inheritance in my vision, but how do you override methods With Interfaces??
How do you use Interfaces for doing same method in different ways and giving the object to decide what to do according to its concrete type?
Thanks
As stated by Andreas Hartl in his article on Inheritance Vs. Interfaces:
Many high-level languages support inheritance and interfaces, and for
someone new to the concepts, it's sometimes not clear which one to
choose. Although languages differ in their exact handling of
inheritance and interfaces, the basics are usually the same, so this
tip should be valid for most languages.
Inheritance means that we derive one class (the derived class) from
another class (the base class). The derived class is an extension of
the base class. It contains all the features (methods and data
members) of the base class, can extend it with new features, and can
reimplement virtual methods of the base class. Some languages, like
C++, support multiple inheritance, where a derived class can have
multiple base classes, but usually inheritance is restricted to a
single base class.
Interfaces can usually only define methods and no data members (but C#
for example allows data members in the form of properties within
interfaces), and a class can always implement multiple interfaces. An
interface contains only method definitions without implementations,
and a class that implements an interface supplies the implementation.
So, using inheritance, you write a base class with method
implementations, and when you derive a class from it, this class will
inherit everything from the base class, and is immediately able to use
its features. An interface on the other hand is just a contract of
method signatures, and a class that wants to implement an interface is
forced to supply the implementations for all methods of the interface.
So when do you use which? In some cases, the language already dictates
what you use: if you need your class to have multiple 'parents', you
cannot use inheritance in languages that don't support multiple
inheritance. And if you want to reuse a library object, you have to
use the fitting concept, depending on if that library object is a
class or an interface.
But which to use if you are free to choose? Basically, base classes
describe and implement common behavior of related types, while
interfaces describe functionality that unrelated types can implement.
Inheritance describes 'is a' relationships, interfaces describe
'behaves like' relationships. For example, say that you are writing a
flight simulator. Your basic entity, which you will for example store
in a list, will be 'Airplane'. Your concrete types will be 'Concorde'
and 'Phantom'. So how should you model the three types? Concorde and
Phantom are related, they both are airplanes and share data, like
'Weight' or 'MaxSpeed' and functionality, like 'Accelerate', so we can
model them with inheritance. 'Airplane' will be the base class with
common data and methods, and 'Concorde' and 'Phantom' will derive from
'Airplane'. We could say that both are specialized airplanes, which is
why it's often said that inheritance means specialization. Now assume
that we also add a class 'Pilot' to our program, and we want to give
the user the ability to save the game and load it later. So when he
saves the game, we need to save the state of all Aircrafts and the
state of all Pilots. And we want to do this in one function that takes
just a list of all saveable objects. So how do we model this? To
answer this, we must take a look at the different types we want to
save. Pilots and Airplanes. It's obvious that they are not related at
all. They share no common data and no common functionality. We can see
that writing a base class 'Saveable' and derive both Pilot and
Airplane from it would make little sense, since no code in Saveable
could be reused by Airplane or Pilot, since both have no common
properties. In this case, an interface is the best solution. We can
write an interface 'ISaveable' with a method Save(). Pilot could then
implement ISaveable.Save() by saving his name, while Airplane could
save its current speed and coordinates.
As you can see, a clear image of the relationship between classes
often makes the choice clear: Use inheritance for related types, where
each derived class 'is a' base class. Use interfaces for unrelated
types which have some common functionality.
Here are some more points to consider with inheritance and interfaces:
Interfaces are fixed. When you change an interface, you have to change every class implementing that interface. But when you change a
base class, every derived class will gain the new functionality, which
can both be good (if you make a bugfix in some base class method
implementation, a derived class using that method will gain the bugfix
without you needing to change it) or bad (if a change in the baseclass
introduces a new bug, all derived classes using the method will be
bugged too).
Interfaces are usually more flexible, since in most languages you can only derive from one class, but implement many interfaces
Interfaces help to protect internal classes: Assume class A has an internal object b of class B. When a method in A returns a pointer or
reference to b, the code that called this method now has access to the
whole object b, which can be dangerous if A only wants to expose
certain members of b. This problem can be solved if you create an
interface I with just the members which are safe to expose. When B
implements this interface, and your method in A returns b via an I
pointer or reference, the outside code can only do what you allow
through the interface.
Polymorphism as a concept does not require inheritance, although in many languages inheritance is the only way to achieve it. Some languages, like smalltalk allow you to polymorphically use any type that implements the same set of members and properties. If it looks like a duck, quacks like a duck, and walks like a duck, you can treat it like a duck.
Polymorphism is simply the ability to treat one object as another object, by providing the same way to access and use it as the original object. This is best illustrated by the Liskov Substitution Principle. This is called the "Interface" or sometimes "Contract", because it defines a "signature" that another object can use to do interesting things to the object.
in C#, you can inherit from interfaces or other (non-sealed) classes. The difference is that an interface does not provide any actual storage or methods (only their "signature"), it is merely a definition. You can't instantiate an interface, you can only instantiate an object that implements an interface.
Classes implement an interface (IDisposable, for instance) in the same way you build a house based on blue prints. If you build two houses with the same blueprints, then each house has the exact same "interface", they may have different color paint, or carpeting, but they function in exactly the same way, yet they are two distinctly different houses, with many differences in how various things might function.
When it comes to C#, just know that an interface says what properties or members an object that implements it MUST have. Likewise, in C#, a big difference is that you can inherit multiple interfaces but only ever a single class. (ie public class Test : BaseClass, IDisposable, ITest, IFooBar)
consider this...
public int SomeMethod(SomeBaseClass object)
{
// Pass in a descendant classe that implements / overrides some method in SomebaseClass
}
public int SomeMethod(ISomeInterface intf)
{
// pass in concrete classes that implement some ISomeInterface function
}
This is the basic essence of polymorphic behavior, a common contract, implemented specifically by a specialist class.

Categories

Resources