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?
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.
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.
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.
A subroutine cannot be declared inside an interface.
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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With