Can an Interface contain a variable? [duplicate]

An interface can be a member of a namespace or a class and can contain signatures of the following members:

Methods

Properties

Indexers

Events

Properties can be declared on interfaces. The declaration takes the following form:
The accessor of an interface property does not have a body.

Thus, the purpose of the accessors is to indicate whether the property is read-write, read-only, or write-only.

Example:

// Interface Properties    
interface IEmployee
{
   string Name
   {
      get;
      set;
   }

   int Counter
   {
      get;
   }
}

Implementation:

public class Employee: IEmployee 
{
   public static int numberOfEmployees;

   private int counter;

   private string name;

   // Read-write instance property:
   public string Name
   {
      get
      {
         return name;
      }
      set
      {
         name = value;
      }
   }

   // Read-only instance property:
   public int Counter
   {    
      get    
      {    
         return counter;
      }    
   }

   // Constructor:
   public Employee()
   {
      counter = ++counter + numberOfEmployees;
   }
}  

MainClass:

public class MainClass
{
   public static void Main()
   {    
      Console.Write("Enter number of employees: ");

      string s = Console.ReadLine();

      Employee.numberOfEmployees = int.Parse(s);

      Employee e1 = new Employee();

      Console.Write("Enter the name of the new employee: ");

      e1.Name = Console.ReadLine();  

      Console.WriteLine("The employee information:");

      Console.WriteLine("Employee number: {0}", e1.Counter);

      Console.WriteLine("Employee name: {0}", e1.Name);    
   }    
}

Leave a Comment