Why constants are not allowed in c# interface? [duplicate] - c#

For example, suppose I want an ICar interface and that all implementations will contain the field Year. Does this mean that every implementation has to separately declare Year? Wouldn't it be nicer to simply define this in the interface?

Though many of the other answers are correct at the semantic level, I find it interesting to also approach these sorts of questions from the implementation details level.
An interface can be thought of as a collection of slots, which contain methods. When a class implements an interface, the class is required to tell the runtime how to fill in all the required slots. When you say
interface IFoo { void M(); }
class Foo : IFoo { public void M() { ... } }
the class says "when you create an instance of me, stuff a reference to Foo.M in the slot for IFoo.M.
Then when you do a call:
IFoo ifoo = new Foo();
ifoo.M();
the compiler generates code that says "ask the object what method is in the slot for IFoo.M, and call that method.
If an interface is a collection of slots that contain methods, then some of those slots can also contain the get and set methods of a property, the get and set methods of an indexer, and the add and remove methods of an event. But a field is not a method. There's no "slot" associated with a field that you can then "fill in" with a reference to the field location. And therefore, interfaces can define methods, properties, indexers and events, but not fields.

Interfaces in C# are intended to define the contract that a class will adhere to - not a particular implementation.
In that spirit, C# interfaces do allow properties to be defined - which the caller must supply an implementation for:
interface ICar
{
int Year { get; set; }
}
Implementing classes can use auto-properties to simplify implementation, if there's no special logic associated with the property:
class Automobile : ICar
{
public int Year { get; set; } // automatically implemented
}

Declare it as a property:
interface ICar {
int Year { get; set; }
}

Eric Lippert nailed it, I'll use a different way to say what he said. All of the members of an interface are virtual and they all need to be overridden by a class that inherits the interface. You don't explicitly write the virtual keyword in the interface declaration, nor use the override keyword in the class, they are implied.
The virtual keyword is implemented in .NET with methods and a so-called v-table, an array of method pointers. The override keyword fills the v-table slot with a different method pointer, overwriting the one produced by the base class. Properties, events and indexers are implemented as methods under the hood. But fields are not. Interfaces can therefore not contain fields.

Why not just have a Year property, which is perfectly fine?
Interfaces don't contain fields because fields represent a specific implementation of data representation, and exposing them would break encapsulation. Thus having an interface with a field would effectively be coding to an implementation instead of an interface, which is a curious paradox for an interface to have!
For instance, part of your Year specification might require that it be invalid for ICar implementers to allow assignment to a Year which is later than the current year + 1 or before 1900. There's no way to say that if you had exposed Year fields -- far better to use properties instead to do the work here.

The short answer is yes, every implementing type will have to create its own backing variable. This is because an interface is analogous to a contract. All it can do is specify particular publicly accessible pieces of code that an implementing type must make available; it cannot contain any code itself.
Consider this scenario using what you suggest:
public interface InterfaceOne
{
int myBackingVariable;
int MyProperty { get { return myBackingVariable; } }
}
public interface InterfaceTwo
{
int myBackingVariable;
int MyProperty { get { return myBackingVariable; } }
}
public class MyClass : InterfaceOne, InterfaceTwo { }
We have a couple of problems here:
Because all members of an interface are--by definition--public, our backing variable is now exposed to anyone using the interface
Which myBackingVariable will MyClass use?
The most common approach taken is to declare the interface and a barebones abstract class that implements it. This allows you the flexibility of either inheriting from the abstract class and getting the implementation for free, or explicitly implementing the interface and being allowed to inherit from another class. It works something like this:
public interface IMyInterface
{
int MyProperty { get; set; }
}
public abstract class MyInterfaceBase : IMyInterface
{
int myProperty;
public int MyProperty
{
get { return myProperty; }
set { myProperty = value; }
}
}

Others have given the 'Why', so I'll just add that your interface can define a Control; if you wrap it in a property:
public interface IView {
Control Year { get; }
}
public Form : IView {
public Control Year { get { return uxYear; } } //numeric text box or whatever
}

A lot has been said already, but to make it simple, here's my take.
Interfaces are intended to have method contracts to be implemented by the consumers or classes and not to have fields to store values.
You may argue that then why properties are allowed? So the simple answer is - properties are internally defined as methods only.

Interfaces do not contain any implementation.
Define an interface with a property.
Further you can implement that interface in any class and use this class going forward.
If required you can have this property defined as virtual in the class so that you can modify its behaviour.

Beginning with C# 8.0, an interface may define a default implementation for members, including properties. Defining a default implementation for a property in an interface is rare because interfaces may not define instance data fields.
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/interface-properties
interface IEmployee
{
string Name
{
get;
set;
}
int Counter
{
get;
}
}
public class Employee : IEmployee
{
public static int numberOfEmployees;
private string _name;
public string Name // read-write instance property
{
get => _name;
set => _name = value;
}
private int _counter;
public int Counter // read-only instance property
{
get => _counter;
}
// constructor
public Employee() => _counter = ++numberOfEmployees;
}

For this you can have a Car base class that implement the year field, and all other implementations can inheritance from it.

An interface defines public instance properties and methods. Fields are typically private, or at the most protected, internal or protected internal (the term "field" is typically not used for anything public).
As stated by other replies you can define a base class and define a protected property which will be accessible by all inheritors.
One oddity is that an interface can in fact be defined as internal but it limits the usefulness of the interface, and it is typically used to define internal functionality that is not used by other external code.

Related

Interfaces and shared implementation

I have this interface
public interface IColumn
{
bool IsVisible {get;set;}
bool IsGroupBy { get; set; }
Type CLRType { get; set; }
string GetGroupByString();
string GetFilterString();
}
and i have classes which will inherit from it, for the first 3 properties the implementation is exactly the same.
for string GetGroupByString(); the implementation is the same for all classes except 2
so i made an abstract class called ColumnBase which inherits the IColumn interface and implements all of its members and added backing fields because i need to implement INotifyPropertyChanged.
and made my classes inherit from ColumnBase and i did override the implmentations that are not meant to be the same.
I have a very limited experience with Interfaces and Abstract classes, my question is if you had an Interface and some classes that will inherit from it and you realized that the implementation for some but not all properties and functions is the same, do you create an abstract class and put the default implementation and override it inside the classes that have special implementation?
This will get you answers based on opinion and preference.
IMHO, I think this would be best suited to an abstract class with the two methods requiring differing implementations being declared as abstract methods; using abstract on the methods means that the implementations must have an implementation of that method.
public abstract class ColumnBase
{
public bool IsVisible { get; set; }
public bool IsGroupBy { get; set; }
public Type CLRType { get; set; }
public virtual string GetGroupByString()
{
return "base string";
}
public abstract string GetFilterString();
}
public class ConcreteColumn : ColumnBase
{
public override string GetGroupByString()
{
return "concrete string";
}
public override string GetFilterString()
{
return "who owns the filter string?";
}
}
do you create an abstract class and put the default implementation and override it inside the classes that have special implementation?
Yes, I would do it exactly.Actually it's kind a purpose of abstract classes and virtual / override features.In your case I think you don't need IColumn interface,you can use an abstract class.And implement all common methods inside of it, then if you want to change behavior of a method override it in nested class.
If you mark a method with virtual you can override it in nested classes and you can change the behaviour of this method depends on your current class.You might want take a look at the documentation for more details.
If your derived class is some specialized version of the base class then it would be a good idea to inherit it from the a base class, like class Rectangle : Shape. This why the derived classes are all specialized version of a same thing. For example Rectangle and Circle are in fact, inherently a shape. But consider using interfaces when you have different objects and you want some similar behaviors. For instance, you can serialize a Bird object and a Chair object, even if they have only Name and Age properties, it's not a good idea to derive them form a base class which has a Name and Age properties and Serialize() method, because they are different things. Although the implementation of Serialize() method would be the same in both of them, it's better to have an ISerializable interface and implement it in both classes.

How do I do I make an inherited immutable property mutable in C#?

Consider that I have an interface that contains the following property
interface IFoo
{
Int32 Id { get; }
}
Now say I want to create an IMutableFoo interface. Logically I would think that the following was correct:
interface IMutableFoo: IFoo
{
Int32 Id { set; }
}
My thought is that it would inherit Id and then in my child interface I'd make it settable. To my surprise, this did not work. Instead I get a warning letting me know that I'm in fact overriding the Id in IFoo with the Id in IMutableFoo. I tried changing { set; } to { get; set; } with the same results. How do I do this right? In Java, I would simply add a setId method. How do I do this in C#? Thanks!
There is nothing you can do other than defining a new interface with a new read/write property. This is because there is no concept of inheritance when talking about interfaces; rather, an interface such as IMutableFoo is a promise that its implementers will also implement the interface IFoo. Both interfaces, however, were defined independently and remain independent.
The MSDN documentation contains the phrase "interfaces can inherit other interfaces", but this is IMHO misleading as there is no inheritance going on here. The "derived" interface simply describes a larger set of members that have to be implemented than the "base" interface.
Implementers of an interface such as IMutableFoo can provide the semantics you target with no problem by explicitly implementing IFoo and sharing code between the getters of IMutableFoo.Id and IFoo.Id:
class Foo : IMutableFoo {
// IFoo is implemented explicitly
// "this" is of type Foo, and since IMutableFoo is implemented
// implicitly below, this.Id accesses the Id declared in IMutableFoo
Int32 IFoo.Id { get { return this.Id; } }
// IMutableFoo is implemented implicitly
// It could also be implemented explicitly, but the body of the
// IFoo.Id getter would need to change ("this" would no longer work)
public Int32 Id { get; set; }
}
Unfortunately there is no mechanism that forces implementers to do this, but some good documentation can go a long way here -- even more so if the relationship between IFoo and IMutableFoo is intuitive.
Re-declaration of Id in the descendent interface indeed hides the one in the parent.
I use two different workarounds for this, entailing tradeoffs that I do not particularly like.
1 - Using an abstract or even a non-abstract class instead of a mutable interface.
interface IFoo {
Int32 Id { get; }
}
abstract class MutableFoo: IFoo {
public abstract Int32 Id {get; set;}
}
The biggest drawback is that the users of your library can no longer program to an interface.
2 - Using a method instead of a property.
interface IFoo {
Int32 Id { get; }
}
interface IMutableFoo: IFoo {
void SetId(Int32 value);
}
This is not ideal, because the setter is not idiomatic, and looks disconnected from the getter.
you can do
public interface IFoo
{
Int32 Id { get; }
}
public interface IFooMu : IFoo
{
new Int32 Id { get; set; }
}
class Foo : IFooMu
{
public Int32 Id { get; set; }
}
There is a huge difference between saying a property is "immutable", versus saying it is "read-only". A object property which is "immutable" is one that will never ever change, for any reason, as long as the object in question exists. By contrast a "read-only" property is one which cannot be changed using a property setter, but might potentially be changed via other means.
Your question seems to be about how to have an object support both read-only and read-write interfaces in sensible fashion; Keith Nicholas' answer illustrates the proper method. Note that if one uses explicit interface implementation, or if one writes the class in vb.net rather than c#, it will be necessary to have separate implementations of both IFooMu.Id and IFoo.Id; that is an annoying requirement imposed by .net, but c# allows one public property to at as implicit definition for read-only, read-write, and write-only properties.

Generic List of Generic Interfaces not allowed, any alternative approaches?

I am trying to find the right way to use a Generic List of Generic Interfaces as a variable.
Here is an example. It is probably not the best, but hopefully you will get the point:
public interface IPrimitive<T>
{
T Value { get; }
}
and then in another class, I want to be able to declare a variable that holds a list of objects that implement IPrimitive<T> for arbitrary T.
// I know this line will not compile because I do not define T
List<IPrimitive<T>> primitives = new List<IPrimitives<T>>;
primitives.Add(new Star()); // Assuming Star implements IPrimitive<X>
primitives.Add(new Sun()); // Assuming Sun implements IPrimitive<Y>
Note that the T in IPrimitive<T> could be different for each entry in the list.
Any ideas on how I could setup such a relationship? Alternative Approaches?
public interface IPrimitive
{
}
public interface IPrimitive<T> : IPrimitive
{
T Value { get; }
}
public class Star : IPrimitive<T> //must declare T here
{
}
Then you should be able to have
List<IPrimitive> primitives = new List<IPrimitive>;
primitives.Add(new Star()); // Assuming Star implements IPrimitive
primitives.Add(new Sun()); // Assuming Sun implements IPrimitive
John is correct.
Might I also suggest (if you are using C# 4) that you make your interface covariant?
public interface IPrimitive<out T>
{
T Value { get; }
}
This could save you some trouble later when you need to get things out of the list.
You say it won't work because you don't define T. So define it:
public class Holder<T>
{
public List<IPrimitive<T>> Primitives {get;set;}
}
This is one of the most complicated elements of the c# language though it is incredibly important for building well defined components. As such, c# falls short. However it is definitely possible to make this work.
The trick is to have 3 parts:
A non generic interface that contains all requirements of the interface.
A generic abstract class that implements the non generic interface and performs the type conversions as necessary.
A class that implements the generic abstract class with the appropriately typed results
For example:
public interface INonGenericInterface{
void Execute(object input);
object GetModel();
}
public abstract class IGenericInterfaceBase<T> : INonGenericInterface{
void INonGenericInterface.Execute(object input){
Execute((T) input);
}
object INonGenericInterface.GetModel(){
return GetModel();
}
protected abstract void Execute(T input);
protected abstract T GetModel();
}
public class ImplementingClass : IGenericInterfaceBase<ModelClass>{
protected override void Execute(ModelClass input){ /*Do something with the input */ }
protected override ModelClass GetModel(){ return new ModelClass();}
}
//Extras for demo
public class ModelClass { }
public class ModelClass2 { }
public class ImplementingClass2 : IGenericInterfaceBase<ModelClass2>
{
protected override void Execute(ModelClass2 input) { /*Do something with the input */ }
protected override ModelClass2 GetModel() { return new ModelClass2(); }
}
var agi = new INonGenericInterface[] { new ImplementingClass(), new ImplementingClass2() };
agi[0].Execute(); var model = agi[0].GetModel();
agi[1].Execute(); var model2 = agi[1].GetModel();
//Check the types of the model and model2 objects to see that they are appropriately typed.
This structure is incredibly useful when coordinating classes w/ one another because you're able to indicate that an implementing class will make use of multiple classes and have type checking validate that each class follows established type expectations. In addition, you might consider using an actual class instead of object for the non-generic class so that you can execute functions on the result of the various non-generic calls. Using this same design you can have those classes be generic classes w/ their own implementations and thus create incredibly complex applications.
To OP: Please consider changing the accepted answer to this to raise awareness of the correct approach as all previously stated answers fall short for various reasons and have probably left readers with more questions. This should handle all future questions related to generic classes in a collection.

How to use a class as the base, but hide the class type publically?

I am currently just exposing the properties through a generic interface e.g.
public interface IBaseClass
{
int ID { get; set; }
}
internal class MyBaseClass : IBaseClass
{
public MyBaseClass() { }
public int ID { get; set; }
}
public class MyExposedClass : IBaseClass
{
private MyBaseClass _base = new MyBaseClass();
public int ID
{
get { return _base.ID; }
set { _base.ID = value; }
}
}
Then in my main application I can do:
IBaseClass c = new MyExposedClass();
c.ID = 12345;
But can't do:
MyBaseClass b = new MyBaseClass();
This is my desired behaviour.
However, I was just wondering if this is the correct approach? Or if there was a better way?
If you only want to prevent instantiation you could make MyBaseClass abstract (make it's constructor protected as well - it is a good design) and have MyExposedClass derive from it. If you want to completely hide the type your approach seems fine.
This look fine to me. Making small interfaces makes it easier to write decoupled code.
I don't know if this will help, but you can make your base class protected internal. This would mean that any internal class has access to it as if it were public, or any class (from within and without the assembly) can subclass the base class. It won't prevent people from implementing their own sub class though.
Alternatively, exposing through an Interface would be the best way I'd think.
For this you can opt for explicit implementation like this:
public interface IBaseClass
{
int ID { get; set; }
}
internal class MyBaseClass : IBaseClass
{
public MyBaseClass() { }
public int IBaseClass.ID { get; set; }
}
public class MyExposedClass : IBaseClass
{
private MyBaseClass _base = new MyBaseClass();
public int IBaseClass.ID
{
get { return _base.ID; }
set { _base.ID = value; }
}
}
You can refer to a similar post C# Interfaces. Implicit implementation versus Explicit implementation
Make your base class abstract.
You could expose the interface as public, implement an internal sealed implementation of that class, and use a factory approach to build instances of the desired interface. That way the client will never know when you change your implementation, or if you have multiple implementations of the same base interface plugged in the factory. You could also eliminate the set accessors in the interface and put them in the internal implementation to only expose the properties to the outside world. That way the exterior code has to make less assumptions over your implementation and you are better isolated. Please correct me if I'm having a poor/bad image of this approach.
Edit: The factory would be public and you'd need some sort of "transfer object" to pass data to the factory. That transfer object implementation would be public, together with it's interface.
Your example seems to include a poor example of taking advantage of inheritence. Since you included a single property it and couldnt come up with a better example i am guessing that its real. I would suggest in this case forget the base class and stick the property on the derived.

How do I implement members of internal interfaces

I have been refactoring the codebase of the project that I am currently on so that classes/interfaces which are not useful beyond the confines of the assembly should be declared as internal (rather than public). But I've run into a problem with the following code:
internal interface IFirstInterface
{
...
}
internal interface ISecondInterface
{
IFirstInterface First{ get; }
...
}
public class Implementer : ISecondInterface
{
public IFirstInterface First {get; private set;}
...
}
My questions:
Why do members of internal interfaces have to be publicly implemented? If you implement the interface on an internal class, shouldn't the implemented members be internal? This is not a big issue since the interface members won't be publicly accessible anyway, given the class is internal. It just seems counter intuitive.
The main problem is with the scenario above since I cannot have a public getter for IFirstInterface since it is purportedly an internal interface i.e. I get the following error from the compiler:
Inconsistent accessibility: property
type 'IFirstInterface' is less
accessible than property
'Implementer.First'
Is there any way around this?
Note: I realise that there is probably little value in this refactoring exercise but I thought it would be a good way for me to understand more deeply the implications of the internal modifier.
Just to note - the code you've actually provided does compile, because Implementer is an internal class. The problem comes when Implementer is public.
The way round this is to use explicit interface implementation:
public class Implementer : ISecondInferface
{
private IFirstInterface first;
IFirstInterface ISecondInterface.First { get { return first; } }
}
You can't have the setter in there, because you're explicitly implementing the interface which doesn't define the setter. You could do this as an alternative:
public class Implementer : ISecondInterface
{
internal IFirstInterface First { get; private set; }
IFirstInterface ISecondInterface.First { get { return First; } }
}
It's unfortunate that internal interfaces have public members - it does complicate things like this. It would be strange for a public interface to have an internal member (what would it be internal to - the implementer or the declarer?) but for internal interfaces it makes a lot more sense.
Why do members of internal interfaces have to be publicly implemented?
When you define an interface, you do not define access level for the members, since all interface members are public. Even if the interface as such is internal, the members are still considered public. When you make an implicit implementation of such a member the signature must match, so it needs to be public.
Regarding exposing the getter, I would suggest making an explicit implementation of the interface instead, and creating an internal property to expose the value:
internal IFirstInterface First { get; private set; }
IFirstInterface ISecondInterface.First
{
get { return this.First; }
}
I know this post is a few years old but i think it’s worth noting that you can implement an internal interface on a public class, see the following links:
http://forums.create.msdn.com/forums/p/29808/167820.aspx
http://msdn.microsoft.com/en-us/library/aa664591%28VS.71%29.aspx
An example from the first link:
internal interface ISecretInterface
{
string Property1 { get; }
}
public class PublicClass : ISecretInterface
{
// class property
public string Property1
{
get { return "Foo"; }
}
// interface property
string ISecretInterface.Property1
{
get { return "Secret"; }
}
}

Categories

Resources