✅ Interface in C#
Hello, I have a question, consider the following code:
My question is, an interface is just like an abstract class in the sense that we can' instantiate directly but rather should be instantiated indirectly by using a derived class from it.
When we write:
I don't understand, we are creating a Dog object, this references a dog? What is the
IAnimal
data type? What does it represents and why not use Dog
instead?22 Replies
An interface defines a contract that the class implements.
You use the the interface to allow implementing generic code in the sense that it doesn't care what the underlying type is.
This code can work with anything that is an IAnimal.
That underlying type in your code example is Dog.
Where it matters is when you hand it off to other code, as in my example.
it's mandatory to overwrite methods from an interface even if we don't use them?
if they don't provide a default implementation, yes
you must implement all methods on an interface
Hmm here under the hood, we are referencing a dog in memory, but what does the IAnimal mean?
yeah I see, like if they don't have a body, then we should implement them ?
Yes, although you can throw NotImplementedException for methods you do not support (although best to support everything if possible.)
It just means the variable is of type IAnimal.
You could later assign a different type of animal to that variable.
If the variable was of type Dog you couldn't assign a Cat to it.
oh ok
A variable of type IAnimal can accept either.
on a generic term, it's an animal but under the hood, more precisely it's a dog ?
Exactly.
might be beneficial to read up on polymorphism and inheritance
yep will do so, I'm currently refreshing the OOP concepts
:base(…) is always referring to the interface if you see that too
No
no, it isn't, please don't add in misinformation. interfaces do not have constructors
It was a question forgot ???
Interface is not the same as a base class.
That’s for abstract right ?
doesn't have to be abstract
Private constructor ?
I would assume not because the inheriting class shouldn't have visibility, but these questions are pretty off-topic for this thread. Might want to open up your own question if that's something you need answers for
Oh ok .