microsoft C# .net Interface doubts - c#

How can an access specifier to the member of interface be specified?
We can use interface as in two ways
Inheritance ( IsA relation )
Containment in another class (Has A relation).
In this way of implementation
protected access specifier is applied only to the events which are in inheritance relationship (IsA).
public access specifier is applied to the properties which are generally used as Has A relation (containment).
thz..
dinesh..

All interface members are automatically public.
If inheritance and protected members are your goal, inherit from a base class instead.
If composition is your goal, use interfaces.

Interface members have the same access operator as the interface they're in, that's the point of having an interface. Otherwise you'd have a public interface IFoo, which has an internal member Bar, which would be problematic if code wants to program against IFoo: it can't always access Bar, although it can use IFoo: the type implementing IFoo apparently doesn't implement Bar at that point.
So if you want to have some elements internal for example, use an internal interface for those members.

Related

why abstract class cannot be instantiated ,what is the use of a class which cannot be instantiated

I know and read about abstract class and interface but one point I never understood is that, what is the use of class which cannot be instantiated.
I can use normal class and virtual method instead of abstract class?
what will happen when I instantiate base class?
You typically use an abstract class when you have some set of common functionality to be shared between derived classes. That is, you cannot use an interface because you want to provide some default functionality.
Take a look at the System.IO.Stream class. This class provides some common base functionality, but requires that specific types of streams implement some members in order for it to function. These members are also tagged abstract, which indicates to the compiler and runtime that there is no suitable base-class implementation. A non-abstract class that derives an abstract class must override all inherited abstract members, just like a class that implements an interface must implement all members defined on the interface.
In the stream example, the Read() method is abstract, but the ReadByte() method is not -- because ReadByte() can be implemented in terms of a call to Read(). (Although not optimally, which is why ReadByte() is virtual, so that a more efficient implementation can optionally be provided.) Virtual members are different, because they do have an implementation, but can optionally be overridden. Abstract members have no implementation by default, and must be overridden.
In other words, methods on an abstract class can use other abstract members on the class, even though they have no implementation! This is because a derived non-abstract class is required to provide an implementation -- an implementation is guaranteed to exist at the point that the method is invoked. This is analogous to how you can use members of an interface even though the members have no implementation on the interface, because it's guaranteed that an object implementing the interface must implement all of its members.
Subclasses like MemoryStream and FileStream override all of the abstract methods to form a concrete class, and they can be instantiated. However, you are able to store them in a Stream reference variable and treat them like a generic "black box" stream. This allows you to declare a method that accepts a Stream object, and you don't have to care what kind of stream it actually is.
Stream foo = new Stream(); // Invalid, Stream is abstract.
Stream foo = new MemoryStream(); // Valid.
So, now to summarize the answers to the questions you posed in your title. An abstract class cannot be instantiated because it may contain members that are abstract and have no implementation. The use of an abstract class is twofold: first, to be subclassed and allow the subclasses to share a common implementation of some members, and second, to allow instances of any objects of subclasses to be used through references to the abstract class.
Abstract classes are very useful and it's all about design. If, for example, you have an abstract base class called Shape, which has functions such as 'Draw' and 'Move'. You then inherit the Shape class to create a 'Circle' class and 'Square' class.
The inherited classes both have the functions Draw and Move. Move may have functionality in the base class which the child classes use, but draw functionality is handled by each child.
While you then instantiate a Circle and Square, it is meaningless to have just a 'Shape' object.
Hope that helps.
Abstract and interfaces enable you to share some common logic but you can't instantiate, directlym any of them
To add to cdhowie answer the most relevant differences between interfaces and abstract classes are:
Inheriting from an abstract class forces child classes to be compromised with a chain of hierarchy. With interface different classes implementing it are completely loose from each other.
With abstract classes you can have methods or properties with logic, that is, some code is implemented itself in the abstract class. In interface there is no code or logic thus forcing implementors to write all the logic
Abstract class and interface class are language features both offering some compile time rules and some run time rules aiding design. So far instantiating abstract class or interface class goes, its not possible using the compiler for sure, if one were to program using assembly language for C++ or say intermediate language code/byte code for C# or Java it might be possible to instantiate them as well, I am not sure on this point though. Since at run time there is a type object for both abstract class and interface class.

Why must methods implementing internal interfaces be public

I am developing an internal class that implements an internal interface.
Can anyone explain why I cannot declare my method as internal, why I am getting the following error: "cannot implement an interface member because it is not public".
I know that I have to declare the method as public, but it makes absolutely no sense to me.
What is the point of declaring a method public if both the interface and the class are internal?
Is it not misleading?
I have read a related question on this site. It is not an exact duplicate, because my class is internal.
Simply put: because that's the way the language designers designed it. Even in internal interfaces, the methods are implicitly public. It does make things simple, but it's a pain in other ways.
If you want a public class where you want to "hide" the use of an internal interface, you could use explicit interface implementation - although that has other drawbacks.
Of course, if your class is internal then it doesn't matter that the methods are public anyway - other assemblies aren't going to be able to call the methods because they can't see the type.
I definitely agree that C# (or .NET in general) hasn't been designed as carefully as it might be around internal interfaces.
In terms of exactly why you're getting an error message - section 13.4.4 of the C# 4 spec (interface mapping) is the reason. Implementations are only found for nonstatic public members and explicit interface member implementations - and if there are any unimplemented members in the interface, an error occurs.
I know this is old but maybe someone find it useful. You can accomplish a kind of internal interface methods like this:
internal interface IFoo
{
void MyMethod();
}
public abstract class Foo : IFoo
{
void IFoo.MyMethod()
{
MyMethod();
}
internal abstract void MyMethod();
}
So all your internal classes should derive from Foo and are forced to implement the abstract MyMethod. But you can treat them all as IFoo of course. But those classes outside the assembly won't provide the MyMethod class.
So you have the advantage to treat your classes internally as IFoo and rely on MyMethod. The drawback is that all your classes will need to derive from Foo which can be a problem if you need another base class.
But I found it helpful if the abstract base class is a generic one and the interface is not. Maybe it is useful in some cases.

interface with base class and derived class to achieve multiple inheritance

I got the following code where i would like to know the relationship between those class and interface.
Multiple inheritance wont work with C# but can we implement using interface?
Please tell me whether the following code will complie or not? why it is so ?
I am very confused?
Pleasehelp me out........
public interface MyInterface
{
void Method();
}
public class Base
{
public void Method() { }
}
public class Derived : Base, MyInterface { }
Please tell me whether the following code will complie or not?
Yes, it will - but you could have found that out for yourself just by trying it.
Why it is so?
Quite simply, Derived implements the contract required by MyInterface. It happens to do that via Base which is unaware of the interface, but it still has all the relevant members.
There's a danger here, though - in reality, interfaces are about more than just having appropriate members available for callers; they're about the semantics of those members. A class hierarchy like this only works when the semantics of Base.Method() exactly match the requirements of MyInterface.Method() by coincidence (as opposed to by explicit, declared design). Even if it's valid to start with, the maintainer of Base may decide to make a change to the behaviour of Method which is valid according to what Base.Method has guaranteed, but isn't valid according to what the interface guarantees.
EDIT: In terms of the language specification, this is in section 13.4.4 of the C# 4 spec:
A class or struct must provide implementations of all members of the interfaces that are listed in the base class list of the class or struct. The process of locating implementations of interface members in an implementing class or struct is known as interface mapping.
Interface mapping for a class or struct C locates an implementation for each member of each interface specified in the base class list of C. The implementation of a particular interface member I.M, where I is the interface in which the member M is declared, is determined by examining each class or struct S, starting with C and repeating for each successive base class of C, until a match is located.
[...]
A compile-time error occurs if implementations cannot be located for all members of all interfaces specified in the base class list of C.

Why do interface members have no access modifier? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Why can't I have protected interface members?
as title, in C#. Is there no possibility that someone might want to have a protected or an internal interface?
Because Interface is in crude terms 'a view to the outside world' and since it is for the outside world, there is no point making its members protected or private.
Or in other words, it is a contract with the outside world which specifies that class implementing this interface does a certain set of things. So, hiding some part of it doesn't make sense.
However, interfaces themselves can have access specifiers like protected or internal etc. Thus limiting 'the outside world' to a subset of 'the whole outside world'.
Interface members are always public because the purpose of an interface is to enable other types to access a class or struct. No access modifiers can be applied to interface members.
All the interface methods are Public. You can't create an access modifier in interface. If you want to use one, use Abstract class.
This is due to the nature of the interface. An interface, by definition is a specification.
A rule in .NET specifications dictates that a class that implements an interface will have to implement all members of that interface.
Now if we mark a member private, then the implementing class cannot implement that particular member.
Please see Non Public Members for C# Interfaces
Interfaces are Coding contracts, this is the very reason it won't allow any access modifier other then Public in it's Method signatures.
But an Interface by itself can be Internal but not private or protected, Internal allows access within the assembly which is perfectly fine.

Abstract classes vs Interfaces

I'm a bit confused about the usage of Abstract classes in C#. In C++, it makes sense to define a template which classes inheriting the abstract class can follow. But, in C# doesn't Interface serve the same purpose?
True that abstract classes can have default implementation which is not provided by Interfaces. So if implementation doesn't need to be included in base class, is it better to go for Interfaces?
I still like to provide a default abstract implementation of an interface, assuming it's a substantial interface (and it makes sense). You never know when you might add something to the interface that has an easy default implementation that could be included and given "for free" to anyone who inherits from the abstract base class.
This CodeProject article has a lot of information on the difference between the two including a table comparing and contrasting the features of each.
Interfaces define the contract between classes - the ways classes call each other. A class can implement multiple interfaces, but can only inherit from one abstract class.
True that abstract classes can have default implementation which is not provided by Interfaces. So if implementation doesn't need to be included in base class, is it better to go for Interfaces?
Yes :). If it makes sense to implement some methods in the base class which will be common to all inhereted class you should use an abstract class. If the base class would only be used to define an interface but there is no common logic between the inherited classes, use an interface.
Interfaces and abstract classes serve different goals. Interfaces are used to declare contracts for classes while abstract classes are used to share a common implementation.
If you only use abstract classes, your classes cannot inherit from other classes because C# does not support multiple inheritance. If you only use interfaces, your classes cannot share common code.
public interface IFoo
{
void Bar();
}
public abstract class FooBase : IFoo
{
public abstract void Bar()
{
// Do some stuff usually required for IFoo.
}
}
Now we can use the interface and base implementation in various situations.
public class FooOne : FooBase
{
public override void Bar()
{
base.Bar(); // Use base implementation.
// Do specialized stuff.
}
}
public class FooTwo : FooBase
{
public override void Bar()
{
// Do other specialized stuff.
base.Bar(); // Use base implementation.
// Do more specialized stuff.
}
}
// This class cannot use the base implementation from FooBase because
// of inheriting from OtherClass but it can still implement IFoo.
public class FooThree : OtherClass, IFoo
{
public virtual void Bar()
{
// Do stuff.
}
}
For your first question, Yes.
For your second answer i'll give you some tips I've followed.
Use abstract classes and interfaces in combination to optimize your design trade-offs.
Use an abstract class
When creating a class library which will be widely distributed or reused—especially to clients, use an abstract class in preference to an interface; because, it simplifies versioning.
Use an abstract class to define a common base class for a family of types.
Use an abstract class to provide default behavior.
Subclass only a base class in a hierarchy to which the class logically belongs.
Use an interface
When creating a standalone project which can be changed at will, use an interface in preference to an abstract class; because, it offers more design flexibility.
Use interfaces to introduce polymorphic behavior without subclassing and to model multiple inheritance—allowing a specific type to support numerous behaviors.
Use an interface to design a polymorphic hierarchy for value types.
Use an interface when an immutable contract is really intended.
A well-designed interface defines a very specific range of functionality. Split up interfaces that contain unrelated functionality.
You can implement any number of Interfaces, but can only inherit one Class. So Classes and Interfaces are quite different beasts in C# and you cannot use them interchangeably. In C# abstract classes are still classes, not interfaces.
If you don't have any default/common code, then go with an interface.
An abstract class can also serve as a template, where it defines the steps of some algorithm and the order in which they are called, and derived classes provide the implementation of these steps:
public abstract class Processor
{
// this is the only public method
// implements the order of the separate steps
public void Process()
{
Step1();
Step2();
//...
}
// implementation is provided by derived classes
protected abstract void Step1();
protected abstract void Step2();
}
Whilst it's true that an abstract class with no implementation is equivalent to an interface, interfaces and abstract classes are used for different things.
Interfaces can be used for polymorphism in the most general sense. For example, ICollection is used to define the interface for all collections (there are quite a few). Here it is defining the operations that you want to perform on a certain kind of type. There are many other uses (such as testability, dependency injection etc). Also, interfaces can be mixed and this works both conceptually and technically.
Abstract classes are more to do with templateable behaviour, where virtual methods are a place to 'fill in the gaps'. Obviously you can't mix abstract classes (at least, not in C#).
In C# a large deterrent for the use of abstract classes is that you can only use one. With interfaces you have the advantage of not limiting the base class for the implementation. To this end, I always use an interface even if I create an abstract base class to aid with the implementation.
Often another annoyance of base abstract classes is that they tend to rely on template arguments. This can make it very difficult for the rest of your code to utilize. The easy answer for this is to provide an interface to talk to the abstract class without knowing the type argument of the template class.
Others seem to be typing their answer faster, but allow me to summarize...
Use an interface. If you need to share implementation, you can also create an abstract base class that provides common implementation details.
Note that with C#3, you can provide default behavior for interfaces through the use of extension methods. There are some limitations, though, and abstract classes still have their place.
The rule I follow when modeling is:
Classes(abstract included) and structs model entities.Interfaces model behavior.
Entities implementing an interface can be considered as exhibiting behaviors that the interface(contract) exposes.
This is hinted at in a few of the answers but not explicitly stated.
The fact that you can implement multiple interfaces and only inherit from one base class, as if they were two sides of the same coin, isn't a good way to look at it.
Don't think of interfaces as part of an object hierarchy. They are usually just small parts of functionality (or at least specific if not small) that your real object heirarchy can declare as implementing. Take IDisposable for instance. If you were the one writing that, would you ask yourself whether it should have been an abstract class or an interface? It seems obvious that in this case they are two completely different things. I want to BE disposable. Think ICloneable and IEnumerable. You can implement those in your class without having to try and make your class derive from some unrelated classes like List or Array. Or take IEnumerator. Simply gives a MoveNext type of view to an object. My class can provide that functionality without having to awkwardly be derived from some other sequential collection data type that has nothing to do with my class.
I always prefer interfaces as long as the base class don't have some really "heavy duty" implementation that will save lots of time to the implementers.
giving that .net allows only one base class inheritance, forcing your users to inherit is a huge limitation.
You should always prefer programming to interfaces than to concrete classes.
If you also want to have a default implementation you can still create a base class which implements your interface(s).

Categories