Instances of Interface Type

Ronald Rex 1,666 Reputation points
2023-10-19T00:24:29.13+00:00

Hi Friends. I am trying to get a deep dive understanding of Interfaces and how they give us the ability to have multiple implementations. I was wondering how would this code be used? Thanks !!!

public class MyClass 
{     
public IActionMovie Movie {get; set;} 
}
Developer technologies C#
0 comments No comments
{count} votes

Accepted answer
  1. Anonymous
    2023-10-19T02:01:45.8333333+00:00

    Hi @Ronald Rex , Welcome to Microsoft Q&A,

    An interface defines a contract that a class must adhere to. In this case, IActionMovie is an interface, and any class that implements this interface must provide concrete implementations for the methods or properties defined in the interface.

    1. Define an interface IActionMovie:
    public interface IActionMovie
    {
        void Play();
        string Title { get; set; }
    }
    
    
    1. Create a class that implements the IActionMovie interface:
    public class ActionMovie : IActionMovie
    {
        public string Title { get; set; }
        
        public void Play()
        {
            Console.WriteLine("Playing action movie: " + Title);
        }
    }
    
    1. Use the MyClass to work with an IActionMovie:
    MyClass myObject = new MyClass();
    
    // Set the Movie property with an instance of ActionMovie
    myObject.Movie = new ActionMovie { Title = "Die Hard" };
    
    // Call the Play method on the ActionMovie
    myObject.Movie.Play();
    
    

    User's image

    By setting the Movie property with an instance of a class that implements IActionMovie, you can call the methods and access the properties defined in the interface through the Movie property.

    This allows you to work with various classes that implement the IActionMovie interface within your MyClass without knowing their specific implementations. It provides flexibility and enables polymorphism in your code, making it easier to swap different action movie implementations as long as they adhere to the IActionMovie contract.

    Best Regards,

    Jiale


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". 

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.