I have a helper class that is just a bunch of static methods and would like to subclass the helper class. Some behavior is unique depending on the subclass so I would like to call a virtual method from the base class, but since all the methods are static I can't create a plain virtual method (need object reference in order to access virtual method).
Is there any way around this? I guess I could use a singleton.. HelperClass.Instance.HelperMethod() isn't so much worse than HelperClass.HelperMethod(). Brownie points for anyone that can point out some languages that support virtual static methods.
Edit: OK yeah I'm crazy. Google search results had me thinking I wasn't for a bit there.
I don't think you are crazy. You just want to use what is impossible currently in .NET.
Your request for virtual static method would have so much sense if we are talking about generics.
For example my future request for CLR designers is to allow me to write intereface like this:
public interface ISumable<T>
{
static T Add(T left, T right);
}
and use it like this:
public T Aggregate<T>(T left, T right) where T : ISumable<T>
{
return T.Add(left, right);
}
But it's impossible right now, so I'm doing it like this:
public static class Static<T> where T : new()
{
public static T Value = new T();
}
public interface ISumable<T>
{
T Add(T left, T right);
}
public T Aggregate<T>(T left, T right) where T : ISumable<T>, new()
{
return Static<T>.Value.Add(left, right);
}
Virtual static methods don't make sense. If I call HelperClass.HelperMethod();, why would I expect some random subclass' method to be called? The solution really breaks down when you have 2 subclasses of HelperClass - which one would you use?
If you want to have overrideable static-type methods you should probably go with:
A singleton, if you want the same subclass to be used globally.
A tradition class hierarchy, with a factory or dependency injection, if you want different behavior in different parts of your application.
Choose whichever solution makes more sense in your situation.
You can achieve the same effect by just having a regular static method and then shadow it with the new keyword
public class Base
{
//Other stuff
public static void DoSomething()
{
Console.WriteLine("Base");
}
}
public class SomeClass : Base
{
public new static void DoSomething()
{
Console.WriteLine("SomeClass");
}
}
public class SomeOtherClass : Base
{
}
Then you can call the methods like so
Base.DoSomething(); //Base
SomeClass.DoSomething(); //SomeClass
SomeOtherClass.DoSomething(); //Base
Indeed, this can be done in Delphi. An example:
type
TForm1 = class(TForm)
procedure FormShow(Sender: TObject);
end;
TTestClass = class
public
class procedure TestMethod(); virtual;
end;
TTestDerivedClass = class(TTestClass)
public
class procedure TestMethod(); override;
end;
TTestMetaClass = class of TTestClass;
var
Form1: TForm1;
implementation
{$R *.dfm}
class procedure TTestClass.TestMethod();
begin
Application.MessageBox('base', 'Message');
end;
class procedure TTestDerivedClass.TestMethod();
begin
Application.MessageBox('descendant', 'Message');
end;
procedure TForm1.FormShow(Sender: TObject);
var
sample: TTestMetaClass;
begin
sample := TTestClass;
sample.TestMethod;
sample := TTestDerivedClass;
sample.TestMethod;
end;
Quite interesting. I no longer use Delphi, but I recall being able to very easily create different types of controls on a custom designer canvas using the metaclass feature: the control class, eg. TButton, TTextBox etc. was a parameter, and I could call the appropriate constructor using the actual metaclass argument.
Kind of the poor man's factory pattern :)
I come from Delphi and this is a feature among many that I sorely miss in c#. Delphi would allow you to create typed type references and you could pass the type of a derived class wherever the type of a parent class was needed. This treatment of types as objects had powerful utility. In particular allowing run time determination of meta data. I am horribly mixing syntax here but in c# it would look something like:
class Root {
public static virtual string TestMethod() {return "Root"; }
}
TRootClass = class of TRoot; // Here is the typed type declaration
class Derived : Root {
public static overide string TestMethod(){ return "derived"; }
}
class Test {
public static string Run(){
TRootClass rc;
rc = Root;
Test(rc);
rc = Derived();
Test(rc);
}
public static Test(TRootClass AClass){
string str = AClass.TestMethod();
Console.WriteLine(str);
}
}
would produce:
Root
derived
You are not crazy. What you are referring to is called Late Static Binding; it's been recently added to PHP. There's a great thread that describes it - here: When would you need to use late static binding?
a static method exists outside of an instance of a class. It cannot use any non-static data.
a virtual method will be "overwritten" by an overloaded function depending of the type of an instance.
so you have a clear contradiction between static and virtual.
This is not a problem of support, It is a concept.
Update: I was proven wrong here(see comments):
So I doubt you will find any OOP-Language which will support virtual
static methods.
There is a way to force an inheritance of "abstract static" methods from an abstract generic class. See as follow :
public abstract class Mother<T> where T : Mother<T>, new()
{
public abstract void DoSomething();
public static void Do()
{
(new T()).DoSomething();
}
}
public class ChildA : Mother<ChildA>
{
public override void DoSomething() { /* Your Code */ }
}
public class ChildB : Mother<ChildB>
{
public override void DoSomething() { /* Your Code */ }
}
Example (using the previous Mother):
public class ChildA : Mother<ChildA>
{
public override void DoSomething() { Console.WriteLine("42"); }
}
public class ChildB : Mother<ChildB>
{
public override void DoSomething() { Console.WriteLine("12"); }
}
public class Program
{
static void Main()
{
ChildA.Do(); //42
ChildB.Do(); //12
Console.ReadKey();
}
}
It's not that great since you can inherit from only one abstract class and it will ask you to be lenient with your new() implementation.
More, I think it will be costly memory-wise depending on the size of your inherited classes.
In case you have memory issue, you would have to set every properties/variables after your new in a public method which is an awful way to have default values.
I heard that Delphi suports something like this. It seems it does it by making classes object instances of a metaclass.
I've not seen it work, so I'm not sure that it works, or what's the point for that.
P.S. Please correct me if I'm wrong, since it's not my domain.
Because a virtual method uses the defined type of the instantiated object to determine which implementation to execute, (as opposed to the declared type of the reference variable)
... and static, of course, is all about not caring if there's even an instantiated instance of the class at all...
So these are incompatible.
Bottom line, is if you want to change behavior based on which subclass an instance is, then the methods should have been virtual methods on the base class, not static methods.
But, as you already have these static methods, and now need to override them, you can solve your problem by this:
Add virtual instance methods to the base class that simply delegate to the static methods, and then override those virtual instance wrapper methods (not the static ones) in each derived subclass, as appropriate...
It is actually possible to combine virtual and static for a method or a member by using the keyword new instead of virtual.
Here is an example:
class Car
{
public static int TyreCount = 4;
public virtual int GetTyreCount() { return TyreCount; }
}
class Tricar : Car
{
public static new int TyreCount = 3;
public override int GetTyreCount() { return TyreCount; }
}
...
Car[] cc = new Car[] { new Tricar(), new Car() };
int t0 = cc[0].GetTyreCount(); // t0 == 3
int t1 = cc[1].GetTyreCount(); // t1 == 4
Obviously the TyreCount value could have been set in the overridden GetTyreCount method, but this avoids duplicating the value. It is possible to get the value both from the class and the class instance.
Now can someone find a really intelligent usage of that feature?
Mart got it right with the 'new' keyword.
I actually got here because I needed this type of functionality and Mart's solution works fine. In fact I took it one better and made my base class method abstract to force the programmer to supply this field.
My scenario was as follows:
I have a base class HouseDeed. Each House type is derived from HouseDeed must have a price.
Here is the partial base HouseDeed class:
public abstract class HouseDeed : Item
{
public static int m_price = 0;
public abstract int Price { get; }
/* more impl here */
}
Now lets look at two derived house types:
public class FieldStoneHouseDeed : HouseDeed
{
public static new int m_price = 43800;
public override int Price { get { return m_price; } }
/* more impl here */
}
and...
public class SmallTowerDeed : HouseDeed
{
public static new int m_price = 88500;
public override int Price { get { return m_price; } }
/* more impl here */
}
As you can see I can access the price of the house via type SmallTowerDeed.m_price, and the instance new SmallTowerDeed().Price
And being abstract, this mechanism nags the programmer into supplying a price for each new derived house type.
Someone pointed how 'static virtual' and 'virtual' are conceptually at odds with one another. I disagree. In this example, the static methods do not need access to the instance data, and so the requirements that (1) the price be available via the TYPE alone, and that (2) a price be supplied are met.
An override method provides a new implementation of a member that is inherited from a base class. The method that is overridden by an override declaration is known as the overridden base method. The overridden base method must have the same signature as the override method.
You cannot override a non-virtual or static method. The overridden base method must be virtual, abstract, or override.
An override declaration cannot change the accessibility of the virtual method. Both the override method and the virtual method must have the same access level modifier.
You cannot use the new, static, or virtual modifiers to modify an override method.
An overriding property declaration must specify exactly the same access modifier, type, and name as the inherited property, and the overridden property must be virtual, abstract, or override.
You can use the new keyword
namespace AspDotNetStorefront
{
// This Class is need to override StudioOnlineCommonHelper Methods in a branch
public class StudioOnlineCommonHelper : StudioOnlineCore.StudioOnlineCommonHelper
{
//
public static new void DoBusinessRulesChecks(Page page)
{
StudioOnlineCore.StudioOnlineCommonHelper.DoBusinessRulesChecks(page);
}
}
}
It is possible to simulate the functionality by using the new keyword in the derived class and throwing the NotSupportedException() in the base.
public class BaseClass{
public static string GetString(){
throw new NotSupportedException(); // This is not possible
}
}
public class DerivedClassA : BaseClass {
public static new string GetString(){
return "This is derived class A";
}
}
public class DerivedClassB : BaseClass {
public static new string GetString(){
return "This is derived class B";
}
}
static public void Main(String[] args)
{
Console.WriteLine(DerivedClassA.GetString()); // Prints "This is derived class A"
Console.WriteLine(DerivedClassB.GetString()); // Prints "This is derived class B"
Console.WriteLine(BaseClass.GetString()); // Throws NotSupportedException
}
Due to the fact that it is not possible to detect this condition at compile time and that IntelliSense won't suggest that such function should be implemented in the derived class, this is a potential headache.
One comment also suggested to use NotImplemetedException(). Microsoft's documentation indicates that neither of these exceptions should be handled so any of them should work.
The differences between NotSupportedException and NotImplemetedException are commented in this blog.
You will be able to soon, in C# 11!
From Tutorial: Explore C# 11 feature - static virtual members in interfaces:
C# 11 and .NET 7 include static virtual members in interfaces. This feature enables you to define interfaces that include overloaded operators or other static members.
Related
public abstract class A
{
// constructors omitted
public abstract A Create(SomeData data);
}
public class B : A
{
// constructors omitted
public override A Create(SomeData data)
{
return new B(data);
}
}
What I want is to be able to make the Create method static, so that I can get an instance of B without having to create a useless instance with an empty constructor. (If you're wondering why, A is actually a generic type of the form A<TFoo, TBar>, where TBar corresponds to the derived types. As we all know, you can't instantiate a generic type using a constructor that takes any arguments.)
I am already aware that static methods are decoupled from the object hierarchy, only relying on the name of the type. That means I can't have Create as an abstract method that I force all descendants to implement. Is there another way I can implement this pattern?
Something like this might work, depends on your requirements
public abstract class A
{
public string Data { get; set; }
public static T Create<T>(string data) where T : A, new()
{
return new T() { Data = data };
}
}
public class B : A { }
then can do
A foo = A.Create<B>("foo");
There is simply no way to do this. Inheritance is based off of instance methods in C# and has no equivalent feature for static methods. Another way to implement this pattern though is to require a lambda in lieu of a static method.
For example (you mentioned the actual type was A<TFoo, TBar>)
void UseIt<TFoo, TBar>(A<TFoo, TBar> p, Func<SomeData, TBar> func) {
TBar b = func();
...
}
The consumer doesn't care if Create is static, instance or even called create. Generally all they care about is having a function which takes a SomeData and returns a TBar. Delegates fit this pattern exactly.
I have read through the follow SO articles
C#: How do I call a static method of a base class from a static method of a derived class?
Can I have a base class where each derived class has its own copy of a static property?
What's the correct alternative to static method inheritance?
All seem very close to my question and have good answers, but they do not seem to answer my question other than to say that I need to make the method non-static.
an example:
abstract public class baseClass
{
private static List<string> attributeNames = new List(new string {"property1","property2"});
// code for property definition and access
virtual public static bool ValidAttribtue(string attributeName)
{
if (attributeNames.Contains(attributeName))
return true;
else
return false;
}
}
class derivedA : baseClass
{
private static List<string> attributeNames = new List(new string {"property3","property4"});
// code for property definition and access
public static override bool ValidAttribute(string attributeName)
{
if (attributeNames.Contains(attributeName))
{
return true;
}
else
{
return base.ValidAttribute(attributeName);
}
}
}
class derivedB : baseClass
{
private static List<string> attributeNames = new List(new string {"property10","property11"});
// code for property definition and access
public static override bool ValidAttribute(string attributeName)
{
if (attributeNames.Contains(attributeName))
{
return true;
}
else
{
return base.ValidAttribute(attributeName);
}
}
}
derivedA would have properties 1,2,3,4 while derivedB would have properties 1,2,10,11.
The list of properties seems to be a class specific value and can not be changed at any point. I would think it then would be static.
Is my design wrong in the sense that I am trying to use static methods when they should not be?
The above example makes me think that inheritance of static methods would be needed, yet it seems that trying to do this is a design flaw. Can anyone help me to understand what is wrong with coding or structuring classes in this manner?
Is my design wrong in the sense that I am trying to use static methods when they should not be?
Yes. Aside from anything else, you're trying to declare a static method as virtual (and then override it), which isn't allowed. You're also trying to declare a class called base, when that's a keyword.
Static methods simply aren't polymorphic. The basis of polymorphism is that the execution time type of the instance involved can be different to the compile-time type of the expression, and the implementation is chosen on the basis of the execution time type. That concept doesn't make sense for static methods as there is no instance.
Now of course you can make a static method in a derived class call a static method in the base class - but there won't be any polymorphism anywhere.
As a side note, all of your methods could be written in a more readable way:
// Base class implementation
return attributeNames.Contains(attributeName);
// Derived class implementations
return attributeNames.Contains(attributeName) ||
BaseClass.ValidAttribute(attributeName);
I thought I had this nailed, and then I go and look at some source at work and am left wondering why there are so many contradictions in what I read from msdn and what I am seeing in source....
My understanding is that the virtual keyword can be used in method declarations to allow any deriving classes to override it.
The override keyword would then need to be used in the derived class when implementing the superclass' virtual method....
For example:
public abstract class A
{
public virtual string GetName();
}
public class B:A
{
//assume there are some defined properties.
public override string GetName()
{
return FirstName;
}
}
I have a few questions:
1) Is it really necessary to define a method as virtual if it has no implementation? Surely it can just be overwritten in the subclass without the use of virtual and override?
2) If (1) is incorrect, am I right in thinking that every virtual method must be overridden in the subclass using it....
EDIT:
You're right my code will not compile... I want to know why....I uinderstand your answers but then I saw this:
public abstract class RequestHandler<TRequest, TResponse> : RequestHandler, IRequestHandler<TRequest>, IRequestHandler, IDisposable, ITypedRequestHandler
where TRequest : global::Agatha.Common.Request
where TResponse : global::Agatha.Common.Response, new()
{
protected RequestHandler();
public virtual void AfterHandle(TRequest request);
public virtual void BeforeHandle(TRequest request);
public override Response CreateDefaultResponse();
public TResponse CreateTypedResponse();
public override Response Handle(Request request);
public abstract Response Handle(TRequest request);
}
The above doesnt cause the compiler to complain...
Firstly the above code is invalid. A virtual method still has to have a body with a default implementation. to do what you have done above you would need to use the abstract keyaord instead of virtual.
abstract means that there is no method body provided but that any class deriving from it must implement this method (unless it is abstract too).
I think this pretty much answers your questions....
If it has no implementation then it cannot be virtual, it must be abstract. If it has an implementation that just does nothing then that must be implemented.
The whole point of a virtual class is that it has default behaviour so you can choose whether or not to override it. If it were abstract then you would have to override it (unless you were deriving another abstract class).
Is it really necessary to define a method as virtual if it has no implementation?
You can make the method abstract (it will implicitly make it virtual).
Surely it can just be overwritten in the subclass without the use of virtual and override?
If you just "overwrite" it without explicitly overriding it, it won't be the same method, and calling the method on a variable of the base class won't call the derived method (it won't participate in polymorphism). You would just be "hiding" the method of the base class (the compiler actually warns you about this, if it's really what you want to do you must use the new modifier.)
An example will make it clearer:
class B
{
public virtual void M() { Console.WriteLine("B.M") };
}
class D1 : Base
{
// Hides the base method
public new void M() { Console.WriteLine("D1.M") };
}
class D2 : Base
{
// Overrides the base method
public override void M() { Console.WriteLine("D2.M") };
}
...
D1 d1 = new D1();
d1.M(); // Prints "D1.M"
B b1 = d1;
b1.M(); // Prints "B.M", because D1.M doesn't override B.M
D2 d2 = new D1();
d2.M(); // Prints "D2.M"
B b2 = d2;
b2.M(); // Also prints "D2.M", because D2.M overrides B.M
If (1) is incorrect, am I right in thinking that every virtual method must be overridden in the subclass using it....
No, only if it's abstract... a virtual method can have an implementation, and in that case derived classes are not forced to override it.
1) Is it really necessary to define a method as virtual if it has no implementation? Surely it can just be overwritten in the subclass without the use of virtual and override?
As said in other answers, virtual methods need to have implementations. You are confusing it with abstract.
If you were asking whether virtual methods which do have an implementation need to be declared virtual: In C#, yes, it is necessary. In Java, you can override any old method. It was a C# design decision to require overriding to be specifically allowed with the virtual keyword, so that methods cannot be overridden unless intended by the programmer.
If the programmer has not expressed intent by not using virtual, you can still "override" methods, with the new keyword. However, this works a bit differently. Hopefully this code will help illustrate the concept:
class Program
{
static void Main(string[] args)
{
var baseC = new BaseClass();
var extC = new ExtClass();
var lazyC = new LazyClass();
Console.WriteLine(baseC.NewMethod());
Console.WriteLine(baseC.VirtualOverrideMethod());
Console.WriteLine("---");
Console.WriteLine(extC.NewMethod());
Console.WriteLine(extC.VirtualOverrideMethod());
Console.WriteLine("---");
Console.WriteLine(((BaseClass) extC).NewMethod());
Console.WriteLine(((BaseClass) extC).VirtualOverrideMethod()); // Redundant typecast
Console.WriteLine("---");
Console.WriteLine(lazyC.VirtualOverrideMethod());
Console.ReadKey();
}
public class BaseClass
{
public BaseClass()
{
}
public string NewMethod()
{
return "NewMethod of BaseClass";
}
public virtual string VirtualOverrideMethod()
{
return "VirtualOverrideMethod of BaseClass";
}
}
class ExtClass : BaseClass
{
public new string NewMethod()
{
return "NewMethod of ExtClass";
}
public override string VirtualOverrideMethod()
{
return "VirtualOverrideMethod of ExtClass";
}
}
class LazyClass : BaseClass
{
}
}
Output:
NewMethod of BaseClass
VirtualOverrideMethod of BaseClass
---
NewMethod of ExtClass
VirtualOverrideMethod of ExtClass
---
NewMethod of BaseClass
VirtualOverrideMethod of ExtClass
---
VirtualOverrideMethod of BaseClass
2) If (1) is incorrect, am I right in thinking that every virtual method must be overridden in the subclass using it....
Not at all. virtual is a way of saying, "it's okay if you want to override this method". In fact, I included LazyClass in my code above to show this.
The above doesnt cause the compiler to complain...
I haven't used interfaces much, but that looks like one. In my code, if I change
class ExtClass : BaseClass
{
public new string NewMethod()
{
return "NewMethod of ExtClass";
}
public override string VirtualOverrideMethod()
{
return "VirtualOverrideMethod of ExtClass";
}
}
to:
class ExtClass : BaseClass
{
public new string NewMethod()
{
return "NewMethod of ExtClass";
}
public override string VirtualOverrideMethod()
{
return "VirtualOverrideMethod of ExtClass";
}
}
I get:
error CS0501: 'OverrideTest.Program.ExtClass.VirtualOverrideMethod()' must declare a body because it is not marked abstract, extern, or partial
From Visual Studio 2010. The same goes for the virtual method of my BaseClass.
The need for virtual is dictated by polymorphism. Think about what happens when you redefine a method in a subclass using new:
class Parent
{
void Foo() { Console.WriteLine("Parent"); }
virtual void Bar { Console.WriteLine("Parent"); }
}
class Child : Parent
{
new void Foo() { Console.WriteLine("Child"); } // another method Foo
override void Bar { Console.WriteLine("Child"); }
}
var child = new Child(); // a Child instance
var parent = (Parent)child; // same object, but statically typed as Parent
c.Bar(); // prints "Child"
p.Bar(); // again, prints "Child" -- expected virtual behavior
c.Foo(); // prints "Child"
p.Foo(); // but this prints "Parent"!!
For this reason, classes that are intended to be derived from (i.e. not sealed) should always mark the methods that can be overridden as virtual -- otherwise there will be confusing runtime behavior like above. There's no difference if the parent implementation actually does anything or not; the point is that it behaves differently.
ok, by declaring the method as virtual (and not wishing to override the method in the subclass), you'd be entering the world of method hiding if you were to introduce a method with the same name into the subclass. You have to define it as thus:
public abstract class A
{
public virtual string GetName()
{
return null;
}
}
public class B : A
{
//assume there are some defined properties.
public new string GetName()
{
return FirstName;
}
}
I'd recommend that you think of the abstract override approach:
public abstract class A
{
public abstract string GetName()
}
// to override
public class B : A
{
//assume there are some defined properties.
public override string GetName()
{
return FirstName;
}
}
this would be quite different. I would strongly recommend that you just override the abstract method in the subclass.
However, here's a quick ref on the subject (old but a good read):
http://www.akadia.com/services/dotnet_polymorphism.html
1) Is it really necessary to define a method as virtual if it has no
implementation? Surely it can just be overwritten in the subclass
without the use of virtual and override?
You can use an abstract methods, that have no body, but they if you derive from that class you must to override that method. All abstact methods have to be overriden in child class.
2) If (1) is incorrect, am I right in thinking that every virtual
method must be overridden in the subclass using it....
No, instead, you can use a virtual keyword to have an implementation inside that, but do not making override in a child class mandatory. Gives you more flexibility, from that point of view.
Usauly they use abstract to create rigid constrains for childs, so every child derived from it must implement specified member of base class.
That's exactly the difference between a virtual and an abstract method:
A virtual method can be overridden by derived classes if the choose to. A virtual method may or may not have a default implementation for inheritors to call into, which is done using the base keyword.
An abstract method must be overridden by derived classes. Its constraints are:
It can only be defined in an abstract class.
It cannot have an implementation, since it's up to the inheritors to define its behavior.
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?
Is it possible to override an internal method's behavior?
using System;
class TestClass
{
public string Name { get { return this.ProtectedMethod(); } }
protected string ProtectedMethod()
{
return InternalMethod();
}
string InternalMethod()
{
return "TestClass::InternalMethod()";
}
}
class OverrideClassProgram : TestClass
{ // try to override the internal method ? (doesn't work)
string InternalMethod()
{
return "OverrideClassProgram::InternalMethod()";
}
static int Main(string[] args)
{
// TestClass::InternalMethod()
Console.WriteLine(new TestClass().Name);
// TestClass::InternalMethod() ?? are we just screwed?
Console.WriteLine(new OverrideClassProgram().Name);
return (int)Console.ReadKey().Key;
}
}
I think you've got something confused here. There is an actual keyword "internal", is this what you want?
internal string InternalMethod()
{
return "TestClass::InternalMethod()";
}
But I think what you're really looking for is the "virtual" keyword. This allows you to do an override:
Parent Class
protected virtual string InternalMethod()
{
return "TestClass::InternalMethod()";
}
Child Class
protected override string InternalMethod()
{
return "TestProgram::InternalMethod()";
}
Using the "new" keyword is valid, but it completely reimplements the method. I.e. it breaks polymorphism.
Edit:
Here's a link.
In Java everything is virtual unless it is static/final. In C# you have to explicitly declare an instance method as virtual and then that method cannot be private. This article explains why.
By default all members of a class are private, so if you do not provide an access modifier (other than private of course) the InternalMethod() method in your example is private and cannot be virtual and thus cannot be overridden.
You must change it's access modifier and mark it as virtual and in the child class you must override it for the code to work the way you want it too.
This may not answer your question, but just to add a cent.
Internal denotes that types or members are accessible only within files in the same assembly. They are public to the assembly but having access slightly less than the public in actual.
MSDN Access Modifiers,
A common use of internal access is in
component-based development because it
enables a group of components to
cooperate in a private manner without
being exposed to the rest of the
application code. For example, a
framework for building graphical user
interfaces could provide Control and
Form classes that cooperate using
members with internal access. Since
these members are internal, they are
not exposed to code that is using the
framework
Try using the override keyword ... the new keyword is to call a class constuctor
Sure, it's possible, but in order to override a method, the method needs to be virtual or abstract, same as any other visibility.
class Base
{
internal virtual void Foo()
{
Console.WriteLine("Foo from Base");
}
}
class Derived : Base
{
internal override void Foo()
{
Console.WriteLine("Foo from Derived");
}
}
When you use the new keyword, it's called method hiding, which is not the same thing. If I write this:
class Base
{
internal void Foo()
{
Console.WriteLine("Foo from Base");
}
}
class Derived : Base
{
internal new void Foo()
{
Console.WriteLine("Foo from Derived");
}
}
static void Main()
{
Base b = new Derived();
b.Foo();
}
Then it will execute the Base Foo method, not Derived. In other words it will print Foo from Base. In the first case, it would still have executed the Derived method and printed Foo from Derived.