Interfaces in C#

Interfaces are very intangible and they share the fact that none of them can be created. However, interfaces are even more conceptual than abstract classes because no method bodies are allowed. So an interface is like an abstract class, but nothing, but with abstraction methods, and because there are no methods with the actual code, there is no requirement of any field properties though permission, as well as indicators and events You can consider an interface in the form of an agreement - a class implementing it is necessary to implement all the methods and properties, however, the most important difference is that That when C # allows multiple inheritance, where classes receive more than a single base class, then it actually allows the implementation of several interfaces!


using System;
using System.Collections.Generic;

namespace Interfaces
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Dog> dogs = new List<Dog>();
            dogs.Add(new Dog("Fido"));
            dogs.Add(new Dog("Bob"));
            dogs.Add(new Dog("Adam"));
            dogs.Sort();
            foreach(Dog dog in dogs)
                Console.WriteLine(dog.Describe());
            Console.ReadKey();
        }
    }

    interface IAnimal
    {
        string Describe();

        string Name
        {
            get;
            set;
        }
    }

    class Dog : IAnimal, IComparable
    {
        private string name;

        public Dog(string name)
        {
            this.Name = name;
        }

        public string Describe()
        {
            return "Hello, I'm a dog and my name is " + this.Name;
        }

        public int CompareTo(object obj)
        {
            if(obj is IAnimal)
                return this.Name.CompareTo((obj as IAnimal).Name);
            return 0;
        }

        public string Name
        {
            get { return name; }
            set { name = value; }
        }
    }
}
Share on Google Plus

About It E Research

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment