Inheritance variables in c# - c#

Just for practice I'm trying to write a calculator program. To make it difficult I trying to use some of the advanced inheritance topics I've learned, but not really used. Lets say you have an interface named IMath with one method string DoMath(). Is it possible to have a variable written in the IMath interface that all classes implementing that interface would see new values? So for example my class Add : IMath would have the method DoMath() and in that DoMath() method would change the value of the variable double ITotal which all classes that implement the IMath interface would see the new value.

You cannot specify variables or fields in interfaces, you can only specify:
Methods
Properties
Indexers
Events
See the C# documentation on interfaces for more information about this.
An interface dictates expected behavior, it does not dictate expected implementation. A property can be read as "the ability to retrieve the value of X" or "the ability to provide the value of X", where as a variable is "the ability to store X". This is not the same thing, and interfaces cannot make that guarantee.
If you absolutely need to enforce the presence of a variable, you should use a base class. I would probably look into combining these things, use interfaces for the external interface (ie. how should my calculator function) and base class and inheritance to avoid rewriting the same code over and over.

It sounds like what you're looking for is an abstract base class.
One possible implementation of what you describe is shown below.
public abstract class MathBase
{
public double Total { get; protected set; }
public abstract string DoMath(double value);
protected double ParseValue(string value)
{
double parsedValue;
if (!double.TryParse(value, out parsedValue))
{
throw new ArgumentException(string.Format("The value '{0}' is not a number.", value), "value");
}
return parsedValue;
}
}
public class Add : MathBase
{
public override string DoMath(string value)
{
Total += ParseValue(value);
return Convert.ToString(Total);
}
}
If you wanted every instance of every class that inherits from MathBase to share the same Total value, you would declare it as static:
public abstract class MathBase
{
public static double Total { get; protected set; }
public abstract string DoMath(string value);
}
(although I'm not really sure why you would want this)

You could do something like this:
interface IMath
{
string DoMath();
}
abstract class MathBase : IMath
{
protected double Total { get; set; }
public abstract string DoMath();
}
class Add : MathBase
{
public override string DoMath()
{
this.Total = 2;
return "2";
}
}

Related

Inner class within Interface in C#

The following question shows how to implement an interface that contains a class in java:
inner class within Interface
The code in Java is:
public interface A {
class B {
}
}
I was hoping the same thing was possible in C#, though I haven't yet been able to get anything working.
For reference, I have a class which makes lookups of key values, but the keys aren't named in a way that makes them easy to understand. I'd like to have a compile time lookup for keys, so the interface would be something like:
interface Lookup {
class Keys {
string SomeKey() => "0"
}
}
Which means I suppose I have two questions:
Is it possible to have an interface containing a class?
Is there a better way of having a lookup between two strings (or any other values) that I can reference reliably at compile time?
Simply put no you can't have a class inside an interface.
From your comments you are talking about having a restricted list of available strings for the keys so I'm wondering if you are in fact not looking for a string/string lookup but just want a convenient way of referencing a list of fixed strings. So a class with constants is all you need:
public static class Strings
{
public const string AString = "A";
public const string BString = "B";
public const string CString = "C";
}
Accessed like this:
var s = Strings.AString;
You cannot have an class within an interface in C#. Interfaces are very simple in C#, and only provide a contract of functionality.
If you want to have a mapping between two strings, a Dictionary<string, string> may be of use to you.
An interface can't itself have any instance data. It's implementation however can have any instance data it requires.
For example, a random example that might give you some insight:
public class SomeClass
{
public string Key {get; set;}
}
public interface ISomeInterface
{
string Value { get; set; }
SomeClass SomeClass { get; set;}
}
public class SomeInterfaceImplementation : ISomeInterface
{
public SomeInterfaceImplementation()
{
SomeClass = new SomeClass()
{
Key = "ABC"
};
}
public string Value { get; set; }
public SomeClass SomeClass { get; set; }
}
public class Program
{
public static void Main()
{
var example = new SomeInterfaceImplementation()
{
Value = "A value",
} as ISomeInterface;
Console.WriteLine($"{example.SomeClass.Key} has value '{example.Value}'");
}
}
In the example, the default constructor "generates" a key of ABC. We could implement this any way your logic requires. But you also have a contract that requires "SomeClass" and it's key is present.
Anywhere you want to use the contract, just accept the Interface and not an implementation class.
Additionally, feel free to play with the fiddle:
Most of the answers under this question are no longer true.
Since C# 8.0, when default interface methods were added, it is possible for an interface to have member declaration that declare for example nested type.
The following code is correct for C# 8.0:
public interface IA
{
class B
{
}
}

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

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.

C#: "Cannot create an instance of the static class"

I'm in the process of converting some Java code to C# and stumbled across the following curious thing:
public interface IActivation {
public abstract double func(double inputput);
public static class S1 : IActivation {
public double func(double input) {
if (input > 0) return 1.0;
return 0.0;
}
}
}
SomewhereElse (usage):
protected IActivation activation = new IActivation.S1();
Looking at the original code, it's clear what the intention of this was:
Declare an interface and nested within it several static implementations of that interface (the code contains other implementations of IActivation, e.g. "S2", "S3" etc. which were omitted here).
The typical usage scenario for this was to assign a variable to one specific implementation of that interface. Also, by the way you'd need to instantiate that variable, it's perfectly clear where those specific implementations belong to - in a manner of speaking, the nested declaration would further increase the readability of the code
(e.g. new IActivation.S1(); makes it clear that S1 is a specific implementation of IActivation).
Interestingly, C# does not like the way the whole thing is defined: "Cannot create an instance of the static class 'IActivation.S1". Does anyone know a way of how to refactor that code so that 1. and 2. would be preserved?
In Java, a static inner class has no implicit access to the members of its enclosing type. In C#, all nested types have no such access to their parent type's members; there is no modifier you need to add in C# to trigger this behavior.
In C#, static classes are abstract sealed, so they cannot be created nor derived -- this is not the same meaning as in Java. Additionally, interfaces cannot contain type declarations of their own.
Try something like this:
public interface IActivation {
double Func(double inputput);
}
public class S1 : IActivation {
public static readonly S1 Instance = new S1();
private S1() { }
public double Func(double input) {
if (input > 0) return 1.0;
return 0.0;
}
}
If your goal is to provide default implementations in some "readable" way (though I dispute that IActivator.S1() is inherently more readable...) then you could create a static factory class:
public static class Activator
{
public static S1 S1
{
get
{
return S1.Instance;
// Or you could do this if you make the S1 constructor public:
// return new S1();
}
}
}
However, I dispute the claim that this is more readable or helpful. Visual Studio will, when constructing an object in the context of a particular type, display all of that type's subtypes. So if you do this (| represents the cursor):
IActivator foo = new |
You should get a neat list of all of the classes in your current scope that implement IActivotor.
Do not mark your class as static.
If IActivation does not have to be an interface, you can turn it into an abstract class
public abstract class IActivation
{
public abstract double func(double inputput);
public class S1 : IActivation
{
public override double func(double input)
{
if (input > 0) return 1.0;
return 0.0;
}
}
}
This changes the actual meaning of the code, but allows you to say
var s1 = new IActivation.S1();
Update The main issue I can think of is if you have a class that extends something else and implements this interface it won't work (you can't inherit from two classes). You could then create an interface and an abstract class that implements the abstract class but that's getting a little silly.
Another option is
public interface IActivation {
// ...
}
public class Activation {
public class S1 : IActivation {
// ...
}
}
The advantage is you keep IActivation as an interface, but you have another class littering your namespace.
In both cases, you haven't done a direct port from Java.
The error message itself is clear, the S1 class cannot be static since you are creating an instance of it. Remove the static keyword from S1. Also, the access modifier and abstract modifier are invalid in an interface declaration.
In C#, interfaces cannot declare inner types.
My suggestion here is to use the Factory pattern to get the correct instances instead of nesting types in your interface (this increases coupling/dependencies).
interface IActivation
{
double func(double inputput);
}
public static class ActivationFactory
{
IActivation GetImplA()
{
return new ImplA();
}
IActivation GetImplB()
{
return new ImplB();
}
}
class ImplA : IActivation { }
class ImplB : IActivation { }
use sigleton pattern for each S'i' implementation and tear appart interface and implementation as described above by cdhowie
It seems you don't need factory - unless your S'i' instances have own state?

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.

Categories

Resources