Force a class to implement a specific constructor [duplicate] - c#

Is there a way of forcing a (child) class to have constructors with particular signatures or particular static methods in C# or Java?
You can't obviously use interfaces for this, and I know that it will have a limited usage. One instance in which I do find it useful is when you want to enforce some design guideline, for example:
Exceptions
They should all have the four canonical constructors, but there is no way to enforce it. You have to rely on a tool like FxCop (C# case) to catch these.
Operators
There is no contract that specifies that two classes can be summed (with operator+ in C#)
Is there any design pattern to work around this limitation?
What construct could be added to the language to overcome this limitation in future versions of C# or Java?

Using generics you can force a type argument to have a parameterless constructor - but that's about the limit of it.
Other than in generics, it would be tricky to actually use these restrictions even if they existed, but it could sometimes be useful for type parameters/arguments. Allowing static members in interfaces (or possibly static interfaces) could likewise help with the "generic numeric operator" issue.
I wrote about this a little while ago when facing a similar problem.

Not enforced at compile-time, but I have spent a lot of time looking at similar issues; a generic-enabled maths library, and an efficient (non-default) ctor API are both avaiable in MiscUtil. However, these are only checked at first-usage at runtime. In reality this isn't a big problem - your unit tests should find any missing operator / ctor very quickly. But it works, and very quickly...

You could use the Factory pattern.
interface Fruit{}
interface FruitFactory<F extends Fruit>{
F newFruit(String color,double weight);
Cocktail mixFruits(F f1,F f2);
}
You could then create classes for any type of Fruit
class Apple implements Fruit{}
class AppleFactory implements FruitFactory<Apple>{
public Apple newFruit(String color, double weight){
// create an instance
}
public Cocktail mixFruits(Apple f1,Apple f2){
// implementation
}
}
This does not enforce that you can't create instance in another way than by using the Factory but at least you can specify which methods you would request from a Factory.

Force Constructors
You can't. The closest that you can come is make the default constructor private and then provide a constructor that has parameters. But it still has loopholes.
class Base
{
private Base() { }
public Base(int x) {}
}
class Derived : Base
{
//public Derived() { } won't compile because Base() is private
public Derived(int x) :base(x) {}
public Derived() : base (0) {} // still works because you are giving a value to base
}

The problem in the language is that static methods are really second class citizens (A constructor is also a kind of static method, because you don't need an instance to start with).
Static methods are just global methods with a namespace, they don't really "belong" to the class they are defined in (OK, they have access to private (static) methods in the class, but that's about it).
The problem on the compiler level is that without a class instance you don't have a virtual function table, which means you cannot use all the inheritance and polymorphism stuff.
I think one could make it work by adding a global/static virtual table for each class but if it hasn't been done yet, there's probably a good reason for it.

Here is I would solve it if I were a language designer.
Allow interfaces to include static methods, operators and constructors.
interface IFoo
{
IFoo(int gottaHaveThis);
static Bar();
}
interface ISummable
{
operator+(ISummable a, ISummable b);
}
Don't allow the corresponding new IFoo(someInt) or IFoo.Bar()
Allow constructors to be inherited (just like static methods).
class Foo: IFoo
{
Foo(int gottaHaveThis) {};
static Bar() {};
}
class SonOfFoo: Foo
{
// SonOfFoo(int gottaHaveThis): base(gottaHaveThis); is implicitly defined
}
class DaughterOfFoo: Foo
{
DaughhterOfFoo (int gottaHaveThis) {};
}
Allow the programmer to cast to interfaces and check, if necessary, at run time if the cast is semantically valid even if the class does not specify explicitly.
ISummable PassedFirstGrade = (ISummable) 10;

Unfortunately you can't in C#. Here is a punch at it though:
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Foo.Instance.GetHelloWorld());
Console.ReadLine();
}
}
public class Foo : FooStaticContract<FooFactory>
{
public Foo() // Non-static ctor.
{
}
internal Foo(bool st) // Overloaded, parameter not used.
{
}
public override string GetHelloWorld()
{
return "Hello World";
}
}
public class FooFactory : IStaticContractFactory<Foo>
{
#region StaticContractFactory<Foo> Members
public Foo CreateInstance()
{
return new Foo(true); // Call static ctor.
}
#endregion
}
public interface IStaticContractFactory<T>
{
T CreateInstance();
}
public abstract class StaticContract<T, Factory>
where Factory : IStaticContractFactory<T>, new()
where T : class
{
private static Factory _factory = new Factory();
private static T _instance;
/// <summary>
/// Gets an instance of this class.
/// </summary>
public static T Instance
{
get
{
// Scary.
if (Interlocked.CompareExchange(ref _instance, null, null) == null)
{
T instance = _factory.CreateInstance();
Interlocked.CompareExchange(ref _instance, instance, null);
}
return _instance;
}
}
}
public abstract class FooStaticContract<Factory>
: StaticContract<Foo, Factory>
where Factory : IStaticContractFactory<Foo>, new()
{
public abstract string GetHelloWorld();
}

Well, I know from the wording of your question you are looking for compile-time enforcement. Unless someone else has a brilliant suggestion/hack that will allow you to do this the way you are implying the compiler should, I would suggest that you could write a custom MSbuild task that did this. An AOP framework like PostSharp might help you accomplish this at comiple-time by piggy backing on it's build task model.
But what is wrong with code analysis or run-time enforcement? Maybe it's just preference and I respect that, but I personally have no issues with having CA/FXCop check these things... and if you really want to force downstream implementers of your classes to have constructor signatures, you can always add rules run-time checking in the base class constructor using reflection.
Richard

I'm unsure as to what you are trying to achieve, can you please elaborate? The only reason for forcing a specific constructor or static method accross different classes is to try and execute them dynamically at run time, is this correct?
A constructor is intended to be specific to a particular class, as it is intended to initialise the specific needs of the class. As I understand it, the reason you would want to enforce something in a class hierarchy or interface, is that it is an activity/operation relevant to the process being performed, but may vary in different circumstances. I believe this is the intended benefit of polymorphism, which you can't achieve using static methods.
It would also require knowing the specific type of the class you wanted to call the static method for, which would break all of the polymorphic hiding of differences in behaviour that the interface or abstract class is trying to achieve.
If the behaviour being represented by the constructor is intended to be part of the contract between the client of these classes then I would add it explicitly to the interface.
If a hierarchy of classes have similar initialisation requirements then I would use an abstract base class, however it should be up to the inheriting classes how they find the parameter for that constructor, which may include exposing a similar or identical constructor.
If this is intended to allow you to create different instances at runtime, then I would recommend using a static method on an abstract base class which knows the different needs of all of the concrete classes (you could use dependency injection for this).

Related

How can I force a class to implements constructor?

I have an interface IPopUp:
public interface IPopUp
{
bool IsCancelable {get;}
void Show();
void Close();
Action MainAction{ get; }
Action CancelAction{ get; }
}
I have several implementations for it: IfoPopUp, ErrorPopUp, and LoadingPopUp
I am creating the instances of the PopUps with a PopUpManager instance
public class PopUpManager
{
public void ShowPopUp<T>(string texto) where T:IPopUp
{
ShowPopup (()=>(IPopUp)Activator.CreateInstance (typeof(T)));
}
public void ShowPopUp<T>(string texto,Action mainAction)where T:IPopUp
{
ShowPopup (()=>(IPopUp)Activator.CreateInstance (typeof(T), mainAction));
}
public void ShowPopUp<T>(string texto,Action mainAction,Action cancelAction)where T:IPopUp
{
ShowPopup (()=>(IPopUp)Activator.CreateInstance (typeof(T), mainAction, cancelAction));
}
private void ShowPopup(Func<IPopUp> factoryFunc)
{
if (PopUpShowed != null) {
PopUpShowed.Close ();
}
IPopUp popUp = factoryFunc ();
popUp.Show ();
}
}
I don't know how can I force the IPopUp implementations to implement the 3 types of constructor I am using in the PopUpManager.
Abstract class won't work since it can force constructors...
Any ideas?
You have already found a nice solution to your question. Here some additional insights about forcing a class to implement certain constructors.
Can it be done with an interface ?
The C# language specification 5.0 defines in chapter 13 what an interface is:
An interface defines a contract. A class or struct that implements an
interface must adhere to its contract. An interface may inherit from
multiple base interfaces, and a class or struct may implement multiple
interfaces. Interfaces can contain methods, properties, events, and
indexers. The interface itself does not provide implementations for
the members that it defines. The interface merely specifies the
members that must be supplied by classes or structs that implement the
interface.
Instance constructors are not methods and can't be part of an interface. This is explicitly reminded in 13.2:
An interface cannot contain constants, fields, operators, instance
constructors, destructors, or types, nor can an interface contain
static members of any kind.
There are plenty of reasons that justify this language design choice, and you can find some additional explanations on SO. Note also that other languages have similar constraints. Java for example states that "Interfaces may not be directly instantiated."
Can it be done with an abstract class ?
The C# language specification says in section 10.1.1.1. that:
The abstract modifier is used to indicate that a class is incomplete
and that it is intended to be used only as a base class. (...) An abstract class cannot be instantiated directly, and it is a compile-time error to use the new operator on an abstract class.
Long story short, if you would define three different constructors in an abstract class, the derived classes would have to invoke one of these constructors, but without giving any constraint on their own constructors. Note that this logic also applies to C++ or Java.
The link of the abstract class with its derived classes is like the link between a Shape and the Square, Rectangle and Circle that implement the Shape: the construction paramters for a Rectangle can be very different from the construction parameters of a Circle, so that the Shape can't put constraints on the constructor of its children.
Can it be done with a combination ?
You want the PopupManager to instantiate an IPopUp that has certain properties. Unfortunately, you can't instantiate directly an IPopUp in a safe fashion (Activator.CreateInstance() might trigger an exception).
To make it safe, you could very well force IPopUp to require a setter for MainAction and CancelAction, and add a constructor constraint (e.g. where T:IPopUp, new()) to make sure that an instance can be created without surprise, and the object altered to fit the needs.
But in some case parameters need to be provided at construction. In this case you could consider using the builder pattern or the factory method as you've chosen. Note that in languages that allow interfaces with static members, you could even make three static factory methods mandatory in the IPopUp interface.
I end up by refactoring the class PopUpManager, so it needs a factory delegate to generate the PopUp.
Is much clear, and the responsibility of instantiating PopUps is from the caller that have much sense.
public void ShowPopUp(Func<IPopUp> factoryFuncPopUp)
{
if (PopUpShowed != null) {
PopUpShowed.Close ();
}
IPopUp popUp = factoryFuncPopUp();
popUp.Show ();
}
Anyway I am interested in knowing which approach is best to force a class to implements some constructor.
I had a similar problem. In my case, classes with a specific attribute [SpecialAttribute] were required to have a parameterless constructor.
I added a test to be run on our CI server after each build, where classes with that attribute are searched for, and then Activator.CreateInstance is called. In case of failures due to MissingMethodExceptions, that test "fails" and shows the classes with missing parameterless constructors.
That is not perfect, as the code does still compile. But a failed automated test with a clear message is an important step forward.

Implement a class from Interface having implemented methods as static (.NET) [duplicate]

Why was C# designed this way?
As I understand it, an interface only describes behaviour, and serves the purpose of describing a contractual obligation for classes implementing the interface that certain behaviour is implemented.
If classes wish to implement that behavour in a shared method, why shouldn't they?
Here is an example of what I have in mind:
// These items will be displayed in a list on the screen.
public interface IListItem {
string ScreenName();
...
}
public class Animal: IListItem {
// All animals will be called "Animal".
public static string ScreenName() {
return "Animal";
}
....
}
public class Person: IListItem {
private string name;
// All persons will be called by their individual names.
public string ScreenName() {
return name;
}
....
}
Assuming you are asking why you can't do this:
public interface IFoo {
void Bar();
}
public class Foo: IFoo {
public static void Bar() {}
}
This doesn't make sense to me, semantically. Methods specified on an interface should be there to specify the contract for interacting with an object. Static methods do not allow you to interact with an object - if you find yourself in the position where your implementation could be made static, you may need to ask yourself if that method really belongs in the interface.
To implement your example, I would give Animal a const property, which would still allow it to be accessed from a static context, and return that value in the implementation.
public class Animal: IListItem {
/* Can be tough to come up with a different, yet meaningful name!
* A different casing convention, like Java has, would help here.
*/
public const string AnimalScreenName = "Animal";
public string ScreenName(){ return AnimalScreenName; }
}
For a more complicated situation, you could always declare another static method and delegate to that. In trying come up with an example, I couldn't think of any reason you would do something non-trivial in both a static and instance context, so I'll spare you a FooBar blob, and take it as an indication that it might not be a good idea.
My (simplified) technical reason is that static methods are not in the vtable, and the call site is chosen at compile time. It's the same reason you can't have override or virtual static members. For more details, you'd need a CS grad or compiler wonk - of which I'm neither.
For the political reason, I'll quote Eric Lippert (who is a compiler wonk, and holds a Bachelor of Mathematics, Computer science and Applied Mathematics from University of Waterloo (source: LinkedIn):
...the core design principle of static methods, the principle that gives them their name...[is]...it can always be determined exactly, at compile time, what method will be called. That is, the method can be resolved solely by static analysis of the code.
Note that Lippert does leave room for a so-called type method:
That is, a method associated with a type (like a static), which does not take a non-nullable “this” argument (unlike an instance or virtual), but one where the method called would depend on the constructed type of T (unlike a static, which must be determinable at compile time).
but is yet to be convinced of its usefulness.
Most answers here seem to miss the whole point. Polymorphism can be used not only between instances, but also between types. This is often needed, when we use generics.
Suppose we have type parameter in generic method and we need to do some operation with it. We dont want to instantinate, because we are unaware of the constructors.
For example:
Repository GetRepository<T>()
{
//need to call T.IsQueryable, but can't!!!
//need to call T.RowCount
//need to call T.DoSomeStaticMath(int param)
}
...
var r = GetRepository<Customer>()
Unfortunately, I can come up only with "ugly" alternatives:
Use reflection
Ugly and beats the idea of interfaces and polymorphism.
Create completely separate factory class
This might greatly increase the complexity of the code. For example, if we are trying to model domain objects, each object would need another repository class.
Instantiate and then call the desired interface method
This can be hard to implement even if we control the source for the classes, used as generic parameters. The reason is that, for example we might need the instances to be only in well-known, "connected to DB" state.
Example:
public class Customer
{
//create new customer
public Customer(Transaction t) { ... }
//open existing customer
public Customer(Transaction t, int id) { ... }
void SomeOtherMethod()
{
//do work...
}
}
in order to use instantination for solving the static interface problem we need to do the following thing:
public class Customer: IDoSomeStaticMath
{
//create new customer
public Customer(Transaction t) { ... }
//open existing customer
public Customer(Transaction t, int id) { ... }
//dummy instance
public Customer() { IsDummy = true; }
int DoSomeStaticMath(int a) { }
void SomeOtherMethod()
{
if(!IsDummy)
{
//do work...
}
}
}
This is obviously ugly and also unnecessary complicates the code for all other methods. Obviously, not an elegant solution either!
I know it's an old question, but it's interesting. The example isn't the best. I think it would be much clearer if you showed a usage case:
string DoSomething<T>() where T:ISomeFunction
{
if (T.someFunction())
...
}
Merely being able to have static methods implement an interface would not achieve what you want; what would be needed would be to have static members as part of an interface. I can certainly imagine many usage cases for that, especially when it comes to being able to create things. Two approaches I could offer which might be helpful:
Create a static generic class whose type parameter will be the type you'd be passing to DoSomething above. Each variation of this class will have one or more static members holding stuff related to that type. This information could supplied either by having each class of interest call a "register information" routine, or by using Reflection to get the information when the class variation's static constructor is run. I believe the latter approach is used by things like Comparer<T>.Default().
For each class T of interest, define a class or struct which implements IGetWhateverClassInfo<T> and satisfies a "new" constraint. The class won't actually contain any fields, but will have a static property which returns a static field with the type information. Pass the type of that class or struct to the generic routine in question, which will be able to create an instance and use it to get information about the other class. If you use a class for this purpose, you should probably define a static generic class as indicated above, to avoid having to construct a new descriptor-object instance each time. If you use a struct, instantiation cost should be nil, but every different struct type would require a different expansion of the DoSomething routine.
None of these approaches is really appealing. On the other hand, I would expect that if the mechanisms existed in CLR to provide this sort of functionality cleanly, .net would allow one to specify parameterized "new" constraints (since knowing if a class has a constructor with a particular signature would seem to be comparable in difficulty to knowing if it has a static method with a particular signature).
Short-sightedness, I'd guess.
When originally designed, interfaces were intended only to be used with instances of class
IMyInterface val = GetObjectImplementingIMyInterface();
val.SomeThingDefinedinInterface();
It was only with the introduction of interfaces as constraints for generics did adding a static method to an interface have a practical use.
(responding to comment:) I believe changing it now would require a change to the CLR, which would lead to incompatibilities with existing assemblies.
To the extent that interfaces represent "contracts", it seems quiet reasonable for static classes to implement interfaces.
The above arguments all seem to miss this point about contracts.
Interfaces specify behavior of an object.
Static methods do not specify a behavior of an object, but behavior that affects an object in some way.
Because the purpose of an interface is to allow polymorphism, being able to pass an instance of any number of defined classes that have all been defined to implement the defined interface... guaranteeing that within your polymorphic call, the code will be able to find the method you are calling. it makes no sense to allow a static method to implement the interface,
How would you call it??
public interface MyInterface { void MyMethod(); }
public class MyClass: MyInterface
{
public static void MyMethod() { //Do Something; }
}
// inside of some other class ...
// How would you call the method on the interface ???
MyClass.MyMethod(); // this calls the method normally
// not through the interface...
// This next fails you can't cast a classname to a different type...
// Only instances can be Cast to a different type...
MyInterface myItf = MyClass as MyInterface;
Actually, it does.
As of Mid-2022, the current version of C# has full support for so-called static abstract members:
interface INumber<T>
{
static abstract T Zero { get; }
}
struct Fraction : INumber<Fraction>
{
public static Fraction Zero { get; } = new Fraction();
public long Numerator;
public ulong Denominator;
....
}
Please note that depending on your version of Visual Studio and your installed .NET SDK, you'll either have to update at least one of them (or maybe both), or that you'll have to enable preview features (see Use preview features & preview language in Visual Studio).
See more:
https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/tutorials/static-virtual-interface-members
https://blog.ndepend.com/c-11-static-abstract-members/
https://khalidabuhakmeh.com/static-abstract-members-in-csharp-10-interfaces#:~:text=Static%20abstract%20members%20allow%20each,like%20any%20other%20interface%20definition.
Regarding static methods used in non-generic contexts I agree that it doesn't make much sense to allow them in interfaces, since you wouldn't be able to call them if you had a reference to the interface anyway. However there is a fundamental hole in the language design created by using interfaces NOT in a polymorphic context, but in a generic one. In this case the interface is not an interface at all but rather a constraint. Because C# has no concept of a constraint outside of an interface it is missing substantial functionality. Case in point:
T SumElements<T>(T initVal, T[] values)
{
foreach (var v in values)
{
initVal += v;
}
}
Here there is no polymorphism, the generic uses the actual type of the object and calls the += operator, but this fails since it can't say for sure that that operator exists. The simple solution is to specify it in the constraint; the simple solution is impossible because operators are static and static methods can't be in an interface and (here is the problem) constraints are represented as interfaces.
What C# needs is a real constraint type, all interfaces would also be constraints, but not all constraints would be interfaces then you could do this:
constraint CHasPlusEquals
{
static CHasPlusEquals operator + (CHasPlusEquals a, CHasPlusEquals b);
}
T SumElements<T>(T initVal, T[] values) where T : CHasPlusEquals
{
foreach (var v in values)
{
initVal += v;
}
}
There has been lots of talk already about making an IArithmetic for all numeric types to implement, but there is concern about efficiency, since a constraint is not a polymorphic construct, making a CArithmetic constraint would solve that problem.
Because interfaces are in inheritance structure, and static methods don't inherit well.
What you seem to want would allow for a static method to be called via both the Type or any instance of that type. This would at very least result in ambiguity which is not a desirable trait.
There would be endless debates about whether it mattered, which is best practice and whether there are performance issues doing it one way or another. By simply not supporting it C# saves us having to worry about it.
Its also likely that a compilier that conformed to this desire would lose some optimisations that may come with a more strict separation between instance and static methods.
You can think of the static methods and non-static methods of a class as being different interfaces. When called, static methods resolve to the singleton static class object, and non-static methods resolve to the instance of the class you deal with. So, if you use static and non-static methods in an interface, you'd effectively be declaring two interfaces when really we want interfaces to be used to access one cohesive thing.
To give an example where I am missing either static implementation of interface methods or what Mark Brackett introduced as the "so-called type method":
When reading from a database storage, we have a generic DataTable class that handles reading from a table of any structure. All table specific information is put in one class per table that also holds data for one row from the DB and which must implement an IDataRow interface. Included in the IDataRow is a description of the structure of the table to read from the database. The DataTable must ask for the datastructure from the IDataRow before reading from the DB. Currently this looks like:
interface IDataRow {
string GetDataSTructre(); // How to read data from the DB
void Read(IDBDataRow); // How to populate this datarow from DB data
}
public class DataTable<T> : List<T> where T : IDataRow {
public string GetDataStructure()
// Desired: Static or Type method:
// return (T.GetDataStructure());
// Required: Instantiate a new class:
return (new T().GetDataStructure());
}
}
The GetDataStructure is only required once for each table to read, the overhead for instantiating one more instance is minimal. However, it would be nice in this case here.
FYI: You could get a similar behavior to what you want by creating extension methods for the interface. The extension method would be a shared, non overridable static behavior. However, unfortunately, this static method would not be part of the contract.
Interfaces are abstract sets of defined available functionality.
Whether or not a method in that interface behaves as static or not is an implementation detail that should be hidden behind the interface. It would be wrong to define an interface method as static because you would be unnecessarily forcing the method to be implemented in a certain way.
If methods were defined as static, the class implementing the interface wouldn't be as encapsulated as it could be. Encapsulation is a good thing to strive for in object oriented design (I won't go into why, you can read that here: http://en.wikipedia.org/wiki/Object-oriented). For this reason, static methods aren't permitted in interfaces.
Static classes should be able to do this so they can be used generically. I had to instead implement a Singleton to achieve the desired results.
I had a bunch of Static Business Layer classes that implemented CRUD methods like "Create", "Read", "Update", "Delete" for each entity type like "User", "Team", ect.. Then I created a base control that had an abstract property for the Business Layer class that implemented the CRUD methods. This allowed me to automate the "Create", "Read", "Update", "Delete" operations from the base class. I had to use a Singleton because of the Static limitation.
Most people seem to forget that in OOP Classes are objects too, and so they have messages, which for some reason c# calls "static method".
The fact that differences exist between instance objects and class objects only shows flaws or shortcomings in the language.
Optimist about c# though...
OK here is an example of needing a 'type method'. I am creating one of a set of classes based on some source XML. So I have a
static public bool IsHandled(XElement xml)
function which is called in turn on each class.
The function should be static as otherwise we waste time creating inappropriate objects.
As #Ian Boyde points out it could be done in a factory class, but this just adds complexity.
It would be nice to add it to the interface to force class implementors to implement it. This would not cause significant overhead - it is only a compile/link time check and does not affect the vtable.
However, it would also be a fairly minor improvement. As the method is static, I as the caller, must call it explicitly and so get an immediate compile error if it is not implemented. Allowing it to be specified on the interface would mean this error comes marginally earlier in the development cycle, but this is trivial compared to other broken-interface issues.
So it is a minor potential feature which on balance is probably best left out.
The fact that a static class is implemented in C# by Microsoft creating a special instance of a class with the static elements is just an oddity of how static functionality is achieved. It is isn't a theoretical point.
An interface SHOULD be a descriptor of the class interface - or how it is interacted with, and that should include interactions that are static. The general definition of interface (from Meriam-Webster): the place or area at which different things meet and communicate with or affect each other. When you omit static components of a class or static classes entirely, we are ignoring large sections of how these bad boys interact.
Here is a very clear example of where being able to use interfaces with static classes would be quite useful:
public interface ICrudModel<T, Tk>
{
Boolean Create(T obj);
T Retrieve(Tk key);
Boolean Update(T obj);
Boolean Delete(T obj);
}
Currently, I write the static classes that contain these methods without any kind of checking to make sure that I haven't forgotten anything. Is like the bad old days of programming before OOP.
C# and the CLR should support static methods in interfaces as Java does. The static modifier is part of a contract definition and does have meaning, specifically that the behavior and return value do not vary base on instance although it may still vary from call to call.
That said, I recommend that when you want to use a static method in an interface and cannot, use an annotation instead. You will get the functionality you are looking for.
Static Methods within an Interface are allowed as of c# 9 (see https://www.dotnetcurry.com/csharp/simpler-code-with-csharp-9).
I think the short answer is "because it is of zero usefulness".
To call an interface method, you need an instance of the type. From instance methods you can call any static methods you want to.
I think the question is getting at the fact that C# needs another keyword, for precisely this sort of situation. You want a method whose return value depends only on the type on which it is called. You can't call it "static" if said type is unknown. But once the type becomes known, it will become static. "Unresolved static" is the idea -- it's not static yet, but once we know the receiving type, it will be. This is a perfectly good concept, which is why programmers keep asking for it. But it didn't quite fit into the way the designers thought about the language.
Since it's not available, I have taken to using non-static methods in the way shown below. Not exactly ideal, but I can't see any approach that makes more sense, at least not for me.
public interface IZeroWrapper<TNumber> {
TNumber Zero {get;}
}
public class DoubleWrapper: IZeroWrapper<double> {
public double Zero { get { return 0; } }
}
As per Object oriented concept Interface implemented by classes and
have contract to access these implemented function(or methods) using
object.
So if you want to access Interface Contract methods you have to create object. It is always must that is not allowed in case of Static methods. Static classes ,method and variables never require objects and load in memory without creating object of that area(or class) or you can say do not require Object Creation.
Conceptually there is no reason why an interface could not define a contract that includes static methods.
For the current C# language implementation, the restriction is due to the allowance of inheritance of a base class and interfaces. If "class SomeBaseClass" implements "interface ISomeInterface" and "class SomeDerivedClass : SomeBaseClass, ISomeInterface" also implements the interface, a static method to implement an interface method would fail compile because a static method cannot have same signature as an instance method (which would be present in base class to implement the interface).
A static class is functionally identical to a singleton and serves the same purpose as a singleton with cleaner syntax. Since a singleton can implement an interface, interface implementations by statics are conceptually valid.
So it simply boils down to the limitation of C# name conflict for instance and static methods of the same name across inheritance. There is no reason why C# could not be "upgraded" to support static method contracts (interfaces).
An interface is an OOPS concept, which means every member of the interface should get used through an object or instance. Hence, an interface can not have static methods.
When a class implements an interface,it is creating instance for the interface members. While a static type doesnt have an instance,there is no point in having static signatures in an interface.

Inheritance isn't working properly for generic abstract object factories

I have the following basic object factory for when I want some members of a class hierarchy to have special construction code and any other members to have generic constructors.
My problem here is that TileFactory doesn't have the method GetInstance--my program won't compile if I try to call TileFactory.GetInstance(). Any advice?
public static class ObjectFactory<K>
{
public static T GetInstance<T>() where T : K
{
T obj = (T)Activator.CreateInstance(typeof(T));
return obj;
}
//snip
}
}
//snip
public static class TileFactory : ObjectFactory<Tile>
{
}
Why can't I inherit static classes?
Citation from here:
This is actually by design. There seems to be no good reason to inherit a static class. It has public static members that you can always access via the class name itself. The only reasons I have seen for inheriting static stuff have been bad ones, such as saving a couple of characters of typing.
There may be reason to consider mechanisms to bring static members directly into scope (and we will in fact consider this after the Orcas product cycle), but static class inheritance is not the way to go: It is the wrong mechanism to use, and works only for static members that happen to reside in a static class.
(Mads Torgersen, C# Language PM)
Other opinions from channel9
Inheritance in .NET works only on instance base. Static methods are defined on the type level not on the instance level. That is why overriding doesn't work with static methods/properties/events...
Static methods are only held once in memory. There is no virtual table etc. that is created for them.
If you invoke an instance method in .NET, you always give it the current instance. This is hidden by the .NET runtime, but it happens. Each instance method has as first argument a pointer (reference) to the object that the method is run on. This doesn't happen with static methods (as they are defined on type level). How should the compiler decide to select the method to invoke?
(littleguru)
And as a valuable idea, littleguru has a partial "workaround" for this issue: the Singleton pattern.
http://www.dofactory.com/Patterns/PatternSingleton.aspx
There is no inheritance for static things. A workaround is to use singletons.

Constructors and Inheritance

Lets take an example in C#
public class Foo
{
public Foo() { }
public Foo(int j) { }
}
public class Bar : Foo
{
}
Now, All the public members of Foo is accessible in Bar except the constructor.
I cannot do something like
Bar bb = new Bar(1);
Why the constructors are not inheritable?
UPDATE
I do understand we can chain constructors, but I would like to know why the above construct is not valid. I am sure there should be a valid reason for it.
Constructors are not inheritable because it might cause weird and unintended behavior. More specifically, if you added a new constructor to a base class, all derived classes get an instance of that constructor. That's a bad thing in some cases, because maybe your base class specifies parameters that don't make sense for your derived classes.
A commonly given example for this is that in many languages, the base class for all objects (commonly called "Object") has a constructor with no parameters. If constructors were inherited, this would mean that all objects have a parameterless constructor, and there's no way to say "I want people who make an instance of this class to provide parameters X, Y and Z, otherwise their code shouldn't compile." For many classes, it's important that certain parameters be defined for their proper function, and making constructors non-heritable is part of the way that class authors can guarantee that some parameters are always defined.
Edit to respond to comments: Ramesh points out that if constructors were inherited as he would like them to be, he could always override base class constructors using privately declared constructors in each derived class. That is certainly true, but there it a logistical problem with this strategy. It requires that writers of derived classes have to watch base classes closely and add a private constructor if they want block inheritance of the base class constructor. Not only is this a lot of work for people writing derived classes, this kind of implicit dependency across classes is exactly the sort of thing that can cause weird behavior.
Ramesh - it's not that what you describe would be impossible to add to a language. In general it's not done because that sort of behavior could confuse people and lead to a lot of extra debugging and code writing.
Quintin Robinson provides some very worthwhile responses to this question in the comments that are definitely worth reading.
They are (via chaining), you would have to chain the constructor in your derived object.. IE:
public class Foo
{
public Foo() { }
public Foo(int j) { }
}
public class Bar : Foo
{
public Bar() : base() { }
public Bar(int j) : base(j) { }
}
The constructors in the derived objects will then chain the calls do the constructors in the base objects.
This article provides some more examples if you want further reading.
One reason why you might introduce a constructor into a class is because it makes no sense to have an instance of that class without a specific "dependency". For example, it might be a data-access class that has to have a connection to a database:
public class FooRepository
{
public FooRepository(IDbConnection connection) { ... }
}
If all the public constructors from base classes were available, then a user of your repository class would be able to use System.Object's default constructor to create an invalid instance of your class:
var badRepository = new FooRepository();
Hiding inherited constructors by default means that you can enforce dependencies without worrying about users creating "invalid" instances.
Suppose constructors were inheritable. How would you disable the inherited constructors in the many cases were they don't make sense for a subclass?
Rather than complicating the language with a mechanism to block inheritance, the language designers opted for simply making constructors not inheritable.
The Foo constructor can only know how to initialize a Foo object, so it makes no sense that it should also know how to initialize any potential subclass
public class Bar : Foo
{
public Bar(int i) : base(i) { }
}
The story the constructor tells is: "Hey base class please do whatever work you need to do to be in a good state so that I can go ahead and set up myself properly".
Constructors are not inheritable for design reasons. (Note that this is the same situation in every object-oriented language of which I know.) The simple answer is that in many cases you'd really not want the same constructors as the base class to be available. See this SO thread for some more complete explanations.
Some discussions
Joel's forum
Eric Gunnerson's blog
The basic idea is to provide as much control to the creator as possible. And you can have private bases. How'd you create the object then?
I think you can do the following:
public class Bar : Foo
{
public Bar (int i)
: base (i)
{
}
}
I may be a bit off -- but it's the general idea.
The simple answer is that the language doesn't work that way.
The real question you are asking for though is why it doesn't work that way :-) Well it is an arbitrary choice, and it follows on from C++ and Java (and very possibly many other langauges that influenced C#).
The likely reason is that the compiler will only generate a constructor that takes no arguments and simply calls the parent is that if you want more than what the compiler makes you do it yourself. This is the best choice since odds are you do more than suply calling the parent constructor.
Really, its because the parent constructor wouldn't fully initialize the child object. A constructor is kind of a personal thing in that respect. That's why most languages don't inherit constructors.

C# - Can publicly inherited methods be hidden (e.g. made private to derived class)

Suppose I have BaseClass with public methods A and B, and I create DerivedClass through inheritance.
e.g.
public DerivedClass : BaseClass {}
Now I want to develop a method C in DerivedClass that uses A and B. Is there a way I can override methods A and B to be private in DerivedClass so that only method C is exposed to someone who wants to use my DerivedClass?
It's not possible, why?
In C#, it is forced upon you that if you inherit public methods, you must make them public. Otherwise they expect you not to derive from the class in the first place.
Instead of using the is-a relationship, you would have to use the has-a relationship.
The language designers don't allow this on purpose so that you use inheritance more properly.
For example one might accidentally confuse a class Car to derive from a class Engine to get it's functionality. But an Engine is functionality that is used by the car. So you would want to use the has-a relationship. The user of the Car does not want to have access to the interface of the Engine. And the Car itself should not confuse the Engine's methods with it's own. Nor Car's future derivations.
So they don't allow it to protect you from bad inheritance hierarchies.
What should you do instead?
Instead you should implement interfaces. This leaves you free to have functionality using the has-a relationship.
Other languages:
In C++ you simply specify a modifier before the base class of private, public or protected. This makes all members of the base that were public to that specified access level. It seems silly to me that you can't do the same in C#.
The restructured code:
interface I
{
void C();
}
class BaseClass
{
public void A() { MessageBox.Show("A"); }
public void B() { MessageBox.Show("B"); }
}
class Derived : I
{
public void C()
{
b.A();
b.B();
}
private BaseClass b;
}
I understand the names of the above classes are a little moot :)
Other suggestions:
Others have suggested to make A() and B() public and throw exceptions. But this doesn't make a friendly class for people to use and it doesn't really make sense.
When you, for instance, try to inherit from a List<object>, and you want to hide the direct Add(object _ob) member:
// the only way to hide
[Obsolete("This is not supported in this class.", true)]
public new void Add(object _ob)
{
throw NotImplementedException("Don't use!!");
}
It's not really the most preferable solution, but it does the job. Intellisense still accepts, but at compile time you get an error:
error CS0619: 'TestConsole.TestClass.Add(TestConsole.TestObject)' is obsolete: 'This is not supported in this class.'
That sounds like a bad idea. Liskov would not be impressed.
If you don't want consumers of DerivedClass to be able to access methods DeriveClass.A() and DerivedClass.B() I would suggest that DerivedClass should implement some public interface IWhateverMethodCIsAbout and the consumers of DerivedClass should actually be talking to IWhateverMethodCIsAbout and know nothing about the implementation of BaseClass or DerivedClass at all.
What you need is composition not inheritance.
class Plane
{
public Fly() { .. }
public string GetPilot() {...}
}
Now if you need a special kind of Plane, such as one that has PairOfWings = 2 but otherwise does everything a plane can.. You inherit plane. By this you declare that your derivation meets the contract of the base class and can be substituted without blinking wherever a base class is expected. e.g. LogFlight(Plane) would continue to work with a BiPlane instance.
However if you just need the Fly behavior for a new Bird you want to create and are not willing to support the complete base class contract, you compose instead. In this case, refactor the behavior of methods to reuse into a new type Flight. Now create and hold references to this class in both Plane and Bird.
You don't inherit because the Bird does not support the complete base class contract... ( e.g. it cannot provide GetPilot() ).
For the same reason, you cannot reduce the visibility of base class methods when you override.. you can override and make a base private method public in the derivation but not vice versa. e.g. In this example, if I derive a type of Plane "BadPlane" and then override and "Hide" GetPilot() - make it private; a client method LogFlight(Plane p) will work for most Planes but will blow up for "BadPlane" if the implementation of LogFlight happens to need/call GetPilot(). Since all derivations of a base class are expected to be 'substitutable' wherever a base class param is expected, this has to be disallowed.
#Brian R. Bondy pointed me to an interesting article on Hiding through inheritance and the new keyword.
http://msdn.microsoft.com/en-us/library/aa691135(VS.71).aspx
So as workaround I would suggest:
class BaseClass
{
public void A()
{
Console.WriteLine("BaseClass.A");
}
public void B()
{
Console.WriteLine("BaseClass.B");
}
}
class DerivedClass : BaseClass
{
new public void A()
{
throw new NotSupportedException();
}
new public void B()
{
throw new NotSupportedException();
}
public void C()
{
base.A();
base.B();
}
}
This way code like this will throw a NotSupportedException:
DerivedClass d = new DerivedClass();
d.A();
The only way to do this that I know of is to use a Has-A relationship and only implement the functions you want to expose.
Hiding is a pretty slippery slope. The main issues, IMO, are:
It's dependent upon the design-time
declaration type of the instance,
meaning if you do something like
BaseClass obj = new SubClass(), then
call obj.A(), hiding is defeated. BaseClass.A() will be executed.
Hiding can very easily obscure
behavior (or behavior changes) in
the base type. This is obviously
less of a concern when you own both
sides of the equation, or if calling 'base.xxx' is part of your sub-member.
If you actually do own both sides of the base/sub-class equation, then you should be able to devise a more manageable solution than institutionalized hiding/shadowing.
I would say that if you have a codebase that you are wanting to do this with, it is not the best designed code base. It's typically a sign of a class in one level of the heirarchy needing a certain public signature while another class derived from that class doesn't need it.
An upcoming coding paradigm is called "Composition over Inheritance." This plays directly off of the principles of object-oriented development (especially the Single Responsibility Principle and Open/Closed Principle).
Unfortunately, the way a lot of us developers were taught object-orientation, we have formed a habit of immediately thinking about inheritance instead of composition. We tend to have larger classes that have many different responsibilities simply because they might be contained with the same "Real World" object. This can lead to class hierarchies that are 5+ levels deep.
An unfortunate side-effect that developers don't normally think about when dealing with inheritance is that inheritance forms one of the strongest forms of dependencies that you can ever introduce into your code. Your derived class is now strongly dependant on the class it was inherited from. This can make your code more brittle in the long run and lead to confounding problems where changing a certain behavior in a base class breaks derived classes in obscure ways.
One way to break your code up is through interfaces like mentioned in another answer. This is a smart thing to do anyways as you want a class's external dependencies to bind to abstractions, not concrete/derived types. This allows you to change the implementation without changing the interface, all without effecting a line of code in your dependent class.
I would much rather than maintain a system with hundreds/thousands/even more classes that are all small and loosely-coupled, than deal with a system that makes heavy use of polymorphism/inheritance and has fewer classes that are more tightly coupled.
Perhaps the best resource out there on object-oriented development is Robert C. Martin's book, Agile Software Development, Principles, Patterns, and Practices.
If they're defined public in the original class, you cannot override them to be private in your derived class. However, you could make the public method throw an exception and implement your own private function.
Edit: Jorge Ferreira is correct.
While the answer to the question is "no", there is one tip I wish to point out for others arriving here (given that the OP was sort of alluding to assembly access by 3rd parties). When others reference an assembly, Visual Studio should be honoring the following attribute so it will not show in intellisense (hidden, but can STILL be called, so beware):
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
If you had no other choice, you should be able to use new on a method that hides a base type method, return => throw new NotSupportedException();, and combine it with the attribute above.
Another trick depends on NOT inheriting from a base class if possible, where the base has a corresponding interface (such as IList<T> for List<T>). Implementing interfaces "explicitly" will also hide those methods from intellisense on the class type. For example:
public class GoodForNothing: IDisposable
{
void IDisposable.Dispose() { ... }
}
In the case of var obj = new GoodForNothing(), the Dispose() method will not be available on obj. However, it WILL be available to anyone who explicitly type-casts obj to IDisposable.
In addition, you could also wrap a base type instead of inheriting from it, then hide some methods:
public class MyList<T> : IList<T>
{
List<T> _Items = new List<T>();
public T this[int index] => _Items[index];
public int Count => _Items.Count;
public void Add(T item) => _Items.Add(item);
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
void ICollection<T>.Clear() => throw new InvalidOperationException("No you may not!"); // (hidden)
/*...etc...*/
}

Categories