Sunday, April 19, 2015

Structure with Interface in C#

Recently I have been playing with Structure and it is fun. I have written couple of blog post about structure. Following are links for that.

Structure in C#
Structure with constructor in C#

In this blog post we are going to learn how we can use structure with interface. So like earlier example I’ve created a console application. Now it’s time to write interface which we can implement with structure. Following is a code for that.
using System;

namespace StructureWithMethodAndInterface
{
    interface IPrintable
    {
        void Print();
    }
}
Here you can see that I have simple interface IPrintable which has simple print method. Now let’s create a structure which implement this interface. Following is a code for that.

using System;

namespace StructureWithMethodAndInterface
{
    public struct Employee : IPrintable
    {
        public int EmployeeId { get; set; }

        public string FirstName { get; set; }

        public string LastName { get; set; }

        public void Print()
        {
            Console.WriteLine("Printing Employee");
            Console.WriteLine(EmployeeId);
            Console.WriteLine(FirstName);
            Console.WriteLine(LastName);
        }
    }
}
Here you can see I have created a structure called Employee with few properties and then I have written a Print method as I’m implementing IPrintable interface in Employee structure. In Print method I’m printing properties of Employee structure.  Now let’s test it via following code in our console application.
namespace StructureWithMethodAndInterface
{
    class Program
    {
        static void Main(string[] args)
        {
            IPrintable employee = new Employee
            {
                EmployeeId=1,
                FirstName="Jalpesh",
                LastName="Vadgama"
            };

            employee.Print();
        }
    }
}
Here I have created a object of Employee structure and then I’ have called print method. Now when you run this example. Following is a output as expected.

structure-with-interface-and-methods

That’s it. Hope you like it. Stay tuned for more.

You can find complete source code this structure series on github at - https://github.com/dotnetjalps/StructureCSharp
Share:

0 comments:

Post a Comment

Your feedback is very important to me. Please provide your feedback via putting comments.

Search This Blog
About Me
My Photo

Full Stack Developer,Blogger,Microsoft Mvp, Mentor, Life long learner, 10+ Years of Experience for JavaScript, web and Microsoft technologies. ASP.NET MVC,Web Forms,C#,AngularJs,Golang
Mvp profile
Subscribe to my blog

Enter your email address:

Follow us on facebook
Blog Archive
Total Pageviews