Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement a property in an interface

Tags:

c#

.net

People also ask

How do you declare a property in an interface?

You just specify that there is a property with a getter and a setter, whatever they will do. In the class, you actually implement them. The shortest way to do this is using this { get; set; } syntax. The compiler will create a field and generate the getter and setter implementation for it.

Can we have property in interface?

Like a class, Interface can have methods, properties, events, and indexers as its members. But interfaces will contain only the declaration of the members. The implementation of the interface's members will be given by class who implements the interface implicitly or explicitly.

Should interface have properties?

Yes, An interface should define properties when it really in need.

What are interface properties?

Interface Properties. Interface Properties combines the attention to detail of times past with the tools of today. The firm operates coast-to-coast in a variety of demanding niches from site selection and research to repositioning and development. Risk assessment and decision making at Interface are second to none.


In the interface, you specify the property:

public interface IResourcePolicy
{
   string Version { get; set; }
}

In the implementing class, you need to implement it:

public class ResourcePolicy : IResourcePolicy
{
   public string Version { get; set; }
}

This looks similar, but it is something completely different. In the interface, there is no code. You just specify that there is a property with a getter and a setter, whatever they will do.

In the class, you actually implement them. The shortest way to do this is using this { get; set; } syntax. The compiler will create a field and generate the getter and setter implementation for it.


You mean like this?

class MyResourcePolicy : IResourcePolicy {
    private string version;

    public string Version {
        get {
            return this.version;
        }
        set {
            this.version = value;
        }
    }
}

Interfaces can not contain any implementation (including default values). You need to switch to abstract class.


The simple example of using a property in an interface:

using System;
interface IName
{
    string Name { get; set; }
}

class Employee : IName
{
    public string Name { get; set; }
}

class Company : IName
{
    private string _company { get; set; }
    public string Name
    {
        get
        {
            return _company;
        }
        set
        {
            _company = value;
        }   
    }
}

class Client
{
    static void Main(string[] args)
    {
        IName e = new Employee();
        e.Name = "Tim Bridges";

        IName c = new Company();
        c.Name = "Inforsoft";

        Console.WriteLine("{0} from {1}.", e.Name, c.Name);
        Console.ReadKey();
    }
}
/*output:
 Tim Bridges from Inforsoft.
 */