I'm trying to understand C#, went through the basics and started trying things in ASP.NET Core but couldn't get my head around the interface part.
I understood that an interface is like a contract of what the class should contain and the interface method doesn't have a body, like this for example:
interface IAnimal
{
void animalSound();
}
and then we provide the implementation in the class, like this:
class Pig : IAnimal
{
public void animalSound()
{
Console.WriteLine("The pig says: wee wee");
}
}
However, when I hit the real world (as usual) things are different :)
In ASP.NET Core we can use the IActionResult interface to help us with responses - to return Ok(), NotFound(), etc.
Like in this example
namespace CityInfo1.API.Controllers
{
[ApiController]
[Route("api/cities")]
public class CitiesControllers : ControllerBase
{
[HttpGet]
public IActionResult GetCities()
{
return Ok(CitiesDataStore.Current.Cities);
}
[HttpGet("{id}")]
public IActionResult GetCity(int id)
{
var cityToReturn = CitiesDataStore.Current.Cities
.FirstOrDefault(c => c.Id == id);
if (cityToReturn == null)
{
return NotFound();
}
return Ok(cityToReturn);
}
}
}
But here, IActionResult is actually providing the functionality and implementation of different methods.
Another question, in the IAnimal example, is it mandatory to use the AnimalSound() in the classes that uses this interface? And if so, is it possible to make it optional?