Suppose you have the following class declarations:
public abstract class Foo
{
public class Bar
{
public virtual void DoSomething() { ... }
}
}
Is it possible to override Bar.DoSomething() in a child class of Foo, a la:
public class Quz : Foo
{
public override void Bar::DoSomething() { ... }
}
Obviously that syntax doesn't work, but is something like this possible?
No, but you can still inherit from the Foo.Bar class itself:
public class BarDerived : Foo.Bar
{
public override void DoSomething() { ... }
}
I feel I should explain that doing this will not mean that a class deriving from Foo will all of a sudden have an inner class of BarDerived instead, it just means that there is a class that can be derived from it. There are ways of replacing what type of class you want to use as the inner class, for example:
public class Foo<T>
where T : Foo.Bar
{
private T _bar = new T();
public class Bar
{
public virtual void DoSomething() { ... }
}
}
public class BarDerived : Foo.Bar
{
public override void DoSomething() { ... }
}
public class Quz : Foo<BarDerived> { ... }
No, only if you inherit from Bar
public class Quz : Foo.Bar
{
public override void DoSomething() { ... }
}
Well, if you are following good practices, then the Bar cannot be constructed by any other class then Foo, that said enables the following:
Create a derived class from Foo::Bar in Quz, and override it's DoSomething()
override each method in Foo where Bar is constructed and provide the derived class instead.
the user of Foo should not know the difference in API between Bar and your new derived inner class.
hope this makes sense.
Related
i need to do something like this in c#. But in the Exec(object) i got a compilation error.
public class ParentClass { }
public class class1 : ParentClass
{
}
public class class2 : ParentClass
{
}
public class class3 : ParentClass
{
}
public class MasterClass
{
public void ExecutionMethod(ParentClass myObject)
{
//some code
Exec(myObject);
//some code
}
public void Exec(class1 obj)
{
//some code
}
public void Exec(class2 obj)
{
//some code
}
public void Exec(class3 obj)
{
//some code
}
}
I solved using Reflection but i think must be a better approach, somebody could give me a nice idea
As #ScottChamberlain pointed out in the comments, you don't have any methods that take an argument of type ParentClass.
Take a look at the Liskov substitution principle - if you've done your implementation properly, you can substitute an instance of, for example, class1 for an instance of ParentClass, but the converse is not true at all.
Odds are, you don't need (or want) the overloads anyway. Just have ParentClass be an abstract class with an abstract Execute method that all child classes have to implement, then you can just call Execute on the class directly without bothering with the overloads. Even better, just make ParentClass an interface. (This is sometimes called the Strategy Pattern by the way).
public interface IParent {
void Execute();
}
public class class1 : ParentClass {
//Execute method implementation
}
public class class2 : ParentClass {
// ...
}
public class class3 : ParentClass {
// ....
}
public class MasterClass
{
public void ExecutionMethod(IParent myObject)
{
//some code
myObject.Execute();
//some code
}
}
I suggest you have a look at object-oriented design patterns. Specifically, the strategy pattern for this problem. Anyway, you can implement what you want like this:
public interface IParent
{
void Exec();
}
public class Child1 : IParent
{
void Exec() { /*code*/ }
}
public class Child2 : IParent
{
void Exec() { /*code*/ }
}
public class Child3 : IParent
{
void Exec() { /*code*/ }
}
public class MasterClass
{
public void ExecutionMethod(IParent myObject)
{
//some code
myObject.Exec();
//some code
}
}
You could also use an abstract class instead of an interface, if you wanted the parent class to have some functionality for the Exec method - then the child classes would have to override the method.
You can use command pattern, with dependency injection. I kind of give you an idea below. The concrete implementation will call execute on your receiver ( you logic goes there
public interface ICommand
{
void Execute();
}
public class Command1 : ICommand
{
public void Execute()
{
throw new NotImplementedException();
}
}
public class Command2 : ICommand
{
public void Execute()
{
throw new NotImplementedException();
}
}
public class Command3 : ICommand
{
public void Execute()
{
throw new NotImplementedException();
}
}
public class CommandManager
{
//you should use DI here to inject each concerete implementation of the command
private Dictionary<string, ICommand> _commands;
public CommandManager()
{
_commands = new Dictionary<string, ICommand>();
}
public void Execute(string key)
{
_commands[key].Execute();
}
}
The error your seeing is a result of your class1,2,3 objects being cast as their parent type because of the signature of the ExecutionMethod(xxx).
And not having an overridden method of Exec that takes a type of 'ParentClass' as the argument.
Probably the simplest method is to create an interface:
IDomainObject{}.
public class ParentClass : IDomainObject { }
public void ExecutionMethod(IDomainObject myObject)
{
Exec(myObject);
}
Using the interface in this way will prevent the downcast during the method call.
You need to use an interface here
Try changing ParentClass like this:
public interface IParentClass{}
Then make each of your classes implement it, like this:
public class class1 : IParentClass
{
}
public class class2 : IParentClass
{
}
Then in your MasterClass, try this:
public void ExecutionMethod(IParentClass myObject)
{
//some code
Exec(myObject);
//some code
}
public void Exec(IParentClass obj)
{
//some code
}
And then you can pass in any of your classes that implement the IParentClassinterface.
Now as an enhancement - if you want every implementation of IParentClass to have some methods and properties that you can invoke in your Exec method, do it like so:
public interface IParentClass
{
void DoTheThing();
}
This will force you to have this method in derived classes, so for example, class1 would look like this:
public class class1 : IParentClass
{
public void DoTheThing()
{
// things get done...
}
}
public class class2 : IParentClass
{
public void DoTheThing()
{
// things get done a different way...
}
}
And now in your Exec method, you can invoke like so:
public void Exec(IParentClass obj)
{
obj.DoTheThing();
}
I'm trying to figure out if this is possible:
public abstract class A<T>
{
public void MyFunc() { ... }
}
public MyClass : A<string>
{
}
Is there a way for MyFunc to know that it has been instanced in a clas of type MyClass ?
I think I need to clarify the question some more:
I have a generic abstract class that contains some core functionality accessed through a singleton.
The user is building a derived class to extend functionalities but the class is not instantiated through a new, but rather by the singleton, contained in the A class once it is accessed.
So, you could see the flow as such:
In the beginning, there is the abstract A<T>
The user creates MyClass : A<string>
The user now accesses: MyClass.MyFunc()
The singleton in MyFunc is then creating the instance
The singleton code is as follows:
public abstract class Singleton<T> where T : class
{
private static readonly Lazy<T> _Instance = new Lazy<T>(CreateInstanceOfT);
protected static T Instance => _Instance.Value;
private static T CreateInstanceOfT()
{
return Activator.CreateInstance(typeof(T), true) as T;
}
}
so:
class A<T>
is really:
class A<T> : Singleton<A>
but what I really need is to, somehow, make it like
Singleton<MyClass>
or whatever class is deriving from
A<T>
I hope this clarifies the question.
Yes, you could do something like:
public abstract class A<T>
{
public void MyFunc()
{
if(this.GetType() == typeof(MyClass))
{
// do your magic
}
}
}
public class MyClass : A<string>
{
}
but why?
Seems to me, if I read your question right, that if the instance of A needs to have MyFunc act differently when it is a MyClass, then MyFunc should be virtual, and overridden in MyClass.
public abstract class A<T>
{
public virtual void MyFunc() { ... }
}
public MyClass : A<string>
{
public override void MyFunc() { ... }
}
Say I have a base class like this:
public abstract class MyBaseClass
{
protected void MyMethod(string myVariable)
{
//...
}
}
Then I inherit this class in a separate assembly:
public abstract class MyDerivedClass : MyBaseClass
{
static readonly string MyConstantString = "Hello";
protected void MyMethod()
{
MyMethod(MyConstantString);
}
}
I now want to make sure that any other class that inherits from MyDerivedClass does not have access to the MyBaseClass.MyMethod() method. (To clarify, I still want to be able to call MyDerivedClass.MyMethod() with no parameters)
I tried using protected internal but that didn't work.
Update: I'm trying to do this because the application I'm working on has a bunch of separate programs that use a base class. There are 5 different "types" of programs, each performs a specific, separate function but they all have some common code that I am trying to abstract into this base class. The common code is 99% the same, differing only slightly depending on what type of program is calling it. This is why I have my base class taking a string parameter in the example which then disappears in the derived base class, as that class knows it performs role x so it tells its base class accordingly.
Then I would instead of inheritance use composition in the MyDerivedClass. So all derived classes from this class does not know the methods from MyBaseClass. The class MyBaseClass would i make package visible so it is not possible to use it.
abstract class MyBaseClass
{
void MyMethod(string myVariable)
{
//...
}
}
abstract class MyDerivedClass
{
static readonly string MyConstantString = "Hello";
private MyBaseClass baseClass;
MyDerivedClass(MyBaseClass baseClass)
{
this.baseClass = baseClass;
}
protected void MyMethod()
{
baseClass.MyMethod(MyConstantString);
}
}
The class names should be changed of course.
This is not quite possible. And it may be a sign that your object design might be in trouble, but that's not a question for SO.
You can try a bit more underhanded approach, though:
public abstract class MyBaseClass
{
protected abstract string MyConstantString { get; }
protected void MyMethod()
{
//...
}
}
public abstract class MyDerivedClass : MyBaseClass
{
protected override sealed string MyConstantString => "Hello";
}
Or, more typically, just use the constructor to pass the required argument:
public abstract class MyBaseClass
{
private readonly string myString;
protected MyBaseClass(string myString)
{
this.myString = myString;
}
protected void MyMethod()
{
//...
}
}
public abstract class MyDerivedClass : MyBaseClass
{
protected MyBaseClass() : base("Hello") {}
}
Classes derived from MyDerivedClass have no way to change the argument in either case, the second approach is a bit nicer from inheritance perspective (basically, the type is a closure over an argument of its ancestor type).
You cannot stop inheriting classes from calling this method - you have made it protected so your intent is for it to be accessible to classes that inherit from it, whether directly, or via another sub-class.
If you want to keep the inheritance, the best you can do is to throw an error if the sub-class calls it in MyDerivedClass:
public abstract class MyBaseClass
{
protected void MyMethod(string myVariable)
{
Console.WriteLine(myVariable);
}
}
public abstract class MyDerivedClass : MyBaseClass
{
static readonly string MyConstantString = "Hello";
protected void MyMethod()
{
base.MyMethod(MyConstantString);
}
protected new void MyMethod(string myVariable)
{
throw new Exception("Not allowed");
}
}
public class SubDerivedClass : MyDerivedClass
{
static readonly string MyConstantString = "Hello";
public void Foo()
{
MyMethod(MyConstantString);
}
}
When Foo() is called in SubDerivedClass, it will call MyMethod in DerivedClass, which will throw the Exception.
I have a base class that has some abstract methods on it and there are 21 classes that are inheriting from this base class. Now for one of those abstract methods I want to implement it with a common implementation for 6 of the 21 classes so I thought about creating another base class that would do this.
I am open to suggestions but my main purpose of creating another base class between the current base class and the 21 classes is to keep from repeating the same code in 6 of the 21 classes if I didn't have to.
Here is a sample of code to illustrate the situation:
public abstract class FooBase
{
public abstract string Bar();
public abstract string SomeMethod();
public virtual string OtherMethod()
{
return this.SomeMethod();
}
}
public abstract class AnotherBase : FooBase
{
public abstract string Bar();
public abstract string SomeMethod();
public override OtherMethod()
{
//this is the common method used by 6 of the classes
return "special string for the 6 classes";
}
}
public class Foo1 : FooBase
{
public override string Bar()
{
//do something specific for the Foo1 class here
return "Foo1 special string";
}
public override string SomeMethod()
{
//do something specific for the Foo1 class here
return "Foo1 special string";
}
}
public class Another2 : AnotherBase
{
public override string Bar()
{
//do something specific for the Another2 class here
return "Another special string";
}
public override string SomeMethod()
{
//do something specific for the Another2 class here
return "Another2 special string";
}
}
Yes, you can derive an abstract class from another abstract class
public abstract class FooBase
{
//Base class content
}
public abstract class AnotherBase : FooBase
{
//it is "optional" to make the definition of the abstract methods of the Parent class in here
}
When we say it is optional to define the abstract methods of the parent class inside of the child class, it is mandatory that the child class should be abstract.
public abstract class FooBase
{
public abstract string Bar();
public abstract string SomeMethod();
public abstract string OtherMethod();
}
public abstract class AnotherBase : FooBase
{
public override string OtherMethod()
{
//common method that you wanted to use for 6 of your classes
return "special string for the 6 classes";
}
}
//child class that inherits FooBase where none of the method is defined
public class Foo1 : FooBase
{
public override string Bar()
{
//definition
}
public override string SomeMethod()
{
//definition
}
public override string OtherMethod()
{
//definition
}
}
//child class that inherits AnotheBase that defines OtherMethod
public class Another2 : AnotherBase
{
public override string Bar()
{
//definition
}
public override string SomeMethod()
{
//definition
}
}
So I'm guessing that there will be 5 more classes like Another2 which inherits from AnotherBase that will have a common definition for OtherMethod
Yes, that is entirely possible and frequently done. There is no rule that says that you can have only one base class at the bottommost level of your class hierarchy; subclasses of that class can just as well be abstract and thereby become (somewhat more specialized) base classes for one group of classes indirectly derived from your general base class.
You should specify what exactly those classes do, but.. given the information you provided:
This is the exact problem that the Strategy pattern aims to solve, as shown in the example given in the Head First Design Patterns book.
You have an abstract Duck class, from which other ducks (e.g., RedheadDuck, MallardDuck) derive. The Duck class has a Quack method, that simply displays the string "quack" on the screen.
Now you are told to add a RubberDuck. This guy doesn't quack! So what do you do? Make Quack abstract and let the subclasses decide how to implement this? No, that'll lead to duplicated code.
Instead, you define an IQuackBehaviour interface with a Quack method. From there, you derive two classes, QuackBehaviour and SqueakBehaviour.
public class SqueakBehaviour: IQuackBehaviour
{
public void Quack(){
Console.WriteLine("squeak");
}
}
public class QuackBehaviour: IQuackBehaviour
{
public void Quack(){
Console.WriteLine("quack");
}
}
Now, you compose your ducks with this behaviour as appropriate:
public class MallardDuck : Duck
{
private IQuackBehaviour quackBehaviour = new QuackBehaviour();
public override void Quack()
{
quackBehaviour.Quack();
}
}
public class RubberDuck : Duck
{
private IQuackBehaviour quackBehaviour = new SqueakBehaviour();
public override void Quack()
{
quackBehaviour.Quack();
}
}
You can even inject an instance of IQuackBehaviour through a property if you want the ducks to change their behaviour at runtime.
Sorry for the vague title, but I wasn't sure how to summarize this in one phrase. I have a situation with a lot of redundant C# code, and it really looks like some kind of crafty trick using some property of inheritance or generics would solve this. However, I'm not a terribly experienced programmer (particularly with C#) and just can't quite see the solution.
The situation, in simplified form, looks something like this. I have a bunch of classes that all inherit from one type.
public class Foo : SuperFoo
{
...
public Foo SomeMethod() { ... }
}
public class Bar : SuperFoo
{
...
public Bar SomeMethod() { ... }
}
public class Baz : SuperFoo
{
...
public Baz SomeMethod() { ... }
}
...
public class SuperFoo
{
...
}
The problem comes when collections of these objects need to be processed. My first-draft solution (the bad one) looks like this:
public void SomeEventHasHappened(...)
{
ProcessFoos();
ProcessBars();
ProcessBazes();
...
}
public void ProcessFoos()
{
...
foreach (var foo in fooList)
{
...
foo.SomeMethod();
}
}
public void ProcessBars()
{
...
foreach (var bar in barList)
{
...
bar.SomeMethod();
}
}
...and so on. The problem is that basically all of the code in the ProcessX methods is the same, other than the type of the objects that are being operated on. It would be nice to consolidate all of these into one method for obvious reasons.
My first thought was to just make a generic Process() method that took a List<SuperFoo> as a parameter and just proceed from there. The problem is that a generic SuperFoo does not have a SomeMethod(), and it can't have one because each of the child classes' SomeMethod() has a different return type, so having overrides doesn't work.
I usually add an interface which operates on base types.
interface ISuperFoo
{
public ISuperFoo SomeMethod() { ... }
}
public class Foo : SuperFoo, ISuperFoo
{
// concrete implementation
public Foo SomeMethod() { ... }
// method for generic use, call by base type
public ISuperFoo ISuperFoo.SomeMethod()
{
return SomeMethod();
}
}
public void Processs()
{
...
foreach (var iSuperFoo in list)
{
...
iSuperFoo.SomeMethod();
}
}
Of course it depends what you are using the result for.
Sometimes you can make it easier using generics, but you also can end up in a mess. Sometimes it is just easier to downcast somewhere. Of course, you try to avoid this whenever you can afford it.
Here's an example of how this might work using generics and making SuperFoo an abstract class.
public interface ISuperFoo
{
...
}
public abstract class SuperFoo<T> where T : ISuperFoo
{
public abstract T SomeMethod();
}
public class BazReturn : ISuperFoo
{
...
}
public class Baz: SuperFoo<BazReturn>
{
public override BazReturn SomeMethod()
{
throw new NotImplementedException();
}
}
public class BarReturn : ISuperFoo
{
...
}
public class Bar : SuperFoo<BarReturn>
{
public override BarReturn SomeMethod()
{
throw new NotImplementedException();
}
}
public static class EventHandler
{
public static void SomeEventHasHappened(List<SuperFoo<ISuperFoo>> list)
{
foreach (SuperFoo<ISuperFoo> item in list)
{
ISuperFoo result = item.SomeMethod();
}
}
}
You could replace the ISuperFoo interface with a concrete class if needed, but then you would have to cast the return value which kind of defeats the purpose.
public abstract class SuperFoo<T>
{
public abstract T SomeMethod();
}
public class Foo : SuperFoo<int>
{
public override int SomeMethod()
{
throw new NotImplementedException();
}
}
public static class EventHandler
{
public static void SomeEventHasHappened(List<SuperFoo<int>> list)
{
foreach (SuperFoo<int> item in list)
{
item.SomeMethod();
}
}
}