I am a junior developer who has been working with C# for the past few months. I have been going over some of the fundamentals again by reading the Microsoft documentation and came across a sentence that has some wording I find confusing. The documentation states:
MyClass mc = new MyClass();
MyClass mc2 = mc;
An interface must be initialized together with a class object that implements it. If MyClass implements IMyInterface, you create an instance of IMyInterface as shown in the following example:
IMyInterface iface = new MyClass();
Saying "an interface must be initialized" and "you create an instance of IMyInterface" doesn't make much sense to me, and this is not something I have had to do yet.
To my understanding, MyClass would implement IMyInterface and could then, for example, be passed into a method somewhere that expects an IMyInterface parameter. Since MyClass would have to implement all the necessary interface methods, it would hold up its side of the 'contract' and the method that expects an IMyInterface parameter would be able to interact with it as it pleases (treating it as an IMyInterface at 'surface' level, even though it is an instance of MyClass).
Where does initialising an interface come into play? Am I misunderstanding this sentence and is the documentation perhaps instead saying that
IMyInterface iface = new MyClass();
is what happens implicitly when initialising an object of a class that implements this interface?
I am quite confused as to why this talks about initialising an interface when, in my mind, that defeats the point of an interface.
CodePudding user response:
I think I'm happy with the understanding that all they're saying is that one can't initialise an interface like so:
IMyInterface iface = new IMyInterface();
and instead it must always be initialised using a class that implements the interface:
IMyInterface iface = new ClassThatImplementsThisInterface();
I think I might have read into it a bit too much.
CodePudding user response:
To instantiate an interface means to create a class that derives from the interface.
To my understanding it the line IMyInterface iface = new MyClass();
can be seen both as instantiating an instance of MyClass
and as instantiating an instance of interface IMyInterface
. Of course MyClass
needs to implement IMyInterface
for this to be valid.