Interface

Interface is a data type that can hold properties and functionalities. Interface is reference type variable. So when you pass an interface to a variable or a method, it references variable. This means when you change copied variable, it will change the main variable too. Or changing main variable will change the copied variable.

 

Let’s take a look at the following example to see the usage of Interface,

 

using System;

namespace ZeroToCSharp {
    class Program {
        static void Main(string[] args) {

            IPerson person = new Person(1, "Robert C.", "Martin");

            //To print output
            Console.WriteLine(string.Concat("Person: ", person.Id, " - ", person.Name, " ", person.Surname));
            Console.ReadKey();
        }
    }
    public class Person : IPerson {
        public Person(int id, string name, string surname) {
            Id = id;
            Name = name;
            Surname = surname;
        }
        public int Id { get; set; }
        public string Name { get; set; }
        public string Surname { get; set; }
    }

    public interface IPerson {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Surname { get; set; }
    }
}

 

Output:

Person: 1 - Robert C. Martin

 

 

Let’s see if interface is reference type variable.

 

using System;

namespace ZeroToCSharp {
    class Program {
        static void Main(string[] args) {

            IPerson person1 = new Person(1, "Robert C.", "Martin");
            IPerson person2 = person1;
            person2.Id = 2;
            person2.Name = "Martin";
            person2.Surname = "Fowler";

            //To print output
            Console.WriteLine(string.Concat("Person1: ", person1.Id, " - ", person1.Name, " ", person1.Surname));
            Console.WriteLine(string.Concat("Person2: ", person2.Id, " - ", person2.Name, " ", person2.Surname));
            Console.ReadKey();
        }
    }
    public class Person : IPerson {
        public Person(int id, string name, string surname) {
            Id = id;
            Name = name;
            Surname = surname;
        }
        public int Id { get; set; }
        public string Name { get; set; }
        public string Surname { get; set; }
    }

    public interface IPerson {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Surname { get; set; }
    }
}

 

Output:

Person1: 2 - Martin Fowler
Person2: 2 - Martin Fowler

 

 

0 0 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x