Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we add variables and properties in interfaces in C#.NET?

Tags:

c#

I want to know that how to add variables (i.e. with which access specifier) in interfaces and also can we write property in interfaces in C#.net?

like image 733
Kiran Thokal Avatar asked Dec 22 '09 06:12

Kiran Thokal


People also ask

Can we add properties in interface?

An interface can contain declarations of methods, properties, indexers, and events. However, it cannot contain fields, auto-implemented properties. The following interface declares some basic functionalities for the file operations. You cannot apply access modifiers to interface members.

Can you add variables to interface?

You cannot add fields to an interface. Interface can only contain methods , so only methods , properties , events can be declared inside an interface decleration.In place of field you can use a property.

Should an interface have properties?

Yes, An interface should define properties when it really in need. Please suppose that. There is a IUser interface that has defined a property "Name" then you can use it without worry about if the object didn't implement the property.

What Cannot be declared in interface?

A subroutine cannot be declared inside an interface.


2 Answers

This should have been easy to find on the internet.

Interfaces are contracts to be fulfilled by implementing classes. Hence they can consist of public methods, properties and events (indexers are permitted too).

Variables in Interfaces - NO. Can you elaborate on why you need them? You can have variables in Base classes though.
Properties in Interfaces - Yes, since they are paired methods under the hood.
Members of an interface are implicitly public. You cannot specify access modifiers explicitly

public interface ISampleInterface
{
    // method declaration
    bool CheckSomething(object o);

    // event declaration
    event EventHandler ShapeChanged;

    // Property declaration:
    string Name
    {
        get;
        set;
    }
}

See also

  • Interfaces
  • Interface properties
  • Interface events
like image 63
3 revs Avatar answered Sep 28 '22 07:09

3 revs


Variables in interfaces, I don't think so but I'm not 100% certain?

And yes, you can have properties in interfaces. See the MSDN reference:
Interface Properties (C# Programming Guide)

like image 37
o.k.w Avatar answered Sep 28 '22 08:09

o.k.w