C# Call Base method with another THIS - c#

I have the following method in the base class:
public class Base
{
protected string Make(string param)
{
return this.ClientID + "_" + configParam;
}
}
And i have another class
public class Class2 : Base
{
}
And
public class Class3 : Base
{
//HERE i would like to call Make but with the THIS as Class2, not the current - Class3.
}
Is this possible?
Thanks.

Suppose you want only subclasses of Base to invoke Make, even if it's not their own Make, you can add a protected invoker method (I call it InvokeSiblingMake):
public class Base
{
private string ClientID;
protected string Make(string param)
{
return this.ClientID + "_" + param;
}
protected void InvokeSiblingMake(Base other)
{
other.Make("hello world");
}
}
public class Class2 : Base
{
}
public class Class3 : Base
{
//HERE i would like to call Make but with the THIS as Class2, not the current - Class3.
public void Test(Class2 other)
{
InvokeSiblingMake(other);
}
}

With the structure of the classes that you have Class3 is a sibling of Class2. You inherit from your parents, not your brother and sister. This means there is no way to cleanly call a method on Class2 from within Class3 through means of base.
There are ways around that by giving a Class2 member variable to Class3, however at that point you're not using inheritance. In that approach, Class2 could inherit from System.Object, System.DateTime or any other class you may create yourself. Then you're acting on the object set as the property, and not through inheritance.

Related

How can I inherit from a control class and an abstract class?

I have a class with a method that accepts an argument which must be a Control with expected methods.
I've created an interface with those methods.
I've created an abstract class that inherits from Control and implements the interface putting all methods abstract (this is the type of my argument above).
Then i've created a class that inherits from TableLayoutPanel and implements the interface.
I create an instance of this class but then i cannot use it as the argument.
I know why. But what is the workaround? I know i could add a method to the interface that returns the Control instance. In this case, the TableLayoutPanel, but i wanted to use the instance itself...
Also, i don't want to make casts inside the method that receives the argument, it has to be "compile-time/type safe" to use in a library for example...
class CollapsibleList : Panel
{
public void AddItem(CollapsibleListItem item)
{
someContainer.Controls.Add(item);
item.CollapsibleListItemCollapse();
}
}
public interface ICollapsibleListItem
{
string CollapsibleListItemName { get; }
void CollapsibleListItemCollapse();
void CollapsibleListItemExpand();
}
public abstract class CollapsibleListItem : Control, ICollapsibleListItem
{
public abstract string CollapsibleListItemName { get; }
public abstract void CollapsibleListItemCollapse();
public abstract void CollapsibleListItemExpand();
}
class ListBoxCollapsibleListItem : TableLayoutPanel, ICollapsibleListItem
{
//... implemented interface methods
}
class Main
{
public void SomeMethod()
{
var item = new ListBoxCollapsibleListItem();
var collapsibleList = new CollapsibleList();
collapsibleList.AddItem(item as CollapsibleListItem); //cast error!
}
}
try below,
collapsibleList.AddItem(item as ICollapsibleListItem);

C# class inheritance doesn't work

namespace MyProgram
{
public class ParentClass
{
}
public class childClass : ParentClass
{
public int Normal()
{
return 1;
}
}
}
SomeWhere else:
ParentClass parentc = new ParentClass();
parentc.Normal(); //<-- I can't call the function normal!
I need help, to use it.
Parent does not have a method Normal, so you can't call it. By basic logic, a parent does not inherit its child's methods; it's the other way around.
Move the normal method to the parent class:
public class ParentClass
{
public int Normal()
{
return 1;
}
}
public class childClass : ParentClass
{
}
You have to Create Refferance of Child Class to Acess the Normal(); function .
childClass obj=new childClass();
obj.Normal();
Try something like this;
class ParentClass
{
public int Normal()
{
return 1;
}
}
// Derived class
class ChildClass: ParentClass
{
public int someMethod()
{
return Normal();
}
}
You need to cast the object down.
You do it when you need to apply a child's function to a parent object.
In order to do that, you need to declare you want to cast the object later by using the child constructor when creating the parent, like so:
class foo{}
class goo:foo{ public void DoStuff(){} }
/*.... In the main program ..... */
foo a = new goo(); // Declaring the a, which is of type foo, might be used as a goo later on.
And for useage, cast it down.
((goo)a).DoStuff();
Hope it helps :)
You cannot call a child class method from parent. But can call parent class method from child.
namespace MyProgram
{
public class ParentClass
{
public int Normal()
{
return 1;
}
}
public class childClass : ParentClass
{
Normal(); // which calls the method in Base class(ParentClass)
//base.Normal(); //or this one in which base tells that the method is in base class
}
}

Can you add a Derived Class to a list of its base class then call a method of the Derived class from the list of base class in C#

Can you add a Derived Class to a list of its base class then call a method of the Derived class from the list of base class(possibly by casting it back to the Derived class since you know it was originally a Derived class)
public class MySystem
{
public string name;
MySystem(string name)
{
this.name = name;
}
public void Update()
{
//dostuff
}
}
public class PowerSystem : MySystem
{
public int totalPower;
PowerSystem (string name, int power) : base(name)
{
this.totalPower = power;
}
public void Update()
{
base.Update();
//Do other stuff
}
}
void Main()
{
List<MySystem> SystemList = new List<MySystem>();
SystemList.Add(new System("Shields"));
SystemList.Add(new System("Hull"));
Power p = new Power("Power", 10);
SystemList.Add(p);
foreach(MainSystems ms in SystemList)
{
if(ms.name != "Power")
ms.Update();
else
(PowerSystem)ms.Update(); //This doesn't work
}
}
So what I'm trying to do is run the update method for every element in the list, with the exeption of the one I named power and instead run the Power.Update method.
The closest post I have found to answering this is here unfortunately I don't fully understand it.
I'm hoping that the list is holding a reference to PowerSystem p and that somehow I can convert it and access the PowerSystem menthod.
I hope this is clear.
Thanks
PS if you have a better idea for this I'm all ears.
Use polymorphism - mark Update in base class virtual and override it in derived class.
Base classes may define and implement virtual methods, and derived
classes can override them, which means they provide their own
definition and implementation. At run-time, when client code calls the
method, the CLR looks up the run-time type of the object, and invokes
that override of the virtual method. Thus in your source code you can
call a method on a base class, and cause a derived class's version of
the method to be executed.
public class MySystem
{
public string name;
MySystem(string name)
{
this.name = name;
}
public virtual void Update()
{
//dostuff
}
}
public class PowerSystem : MySystem
{
public int totalPower;
PowerSystem (string name, int power) : base(name)
{
this.totalPower = power;
}
public override void Update()
{
base.Update();
//Do other stuff
}
}
Now, PowerSystem.Update() will get called automatically
foreach(MainSystems ms in SystemList)
{
ms.Update();
}
For MySystem instances it will call MySystem.Update, but for PowerSystem instances the override will be called.

How to have a sealed constructor?

I have a baseclass which has public contructors.
The baseclass is not sealed and is not abstract.
There is one constructor which I desire to be sealed. Is this possible?
My current attempt results in syntax error saying the constructor cannot be sealed.
public sealed MyBase(string someParam)
Additional:
I wish to be able to instantiate the base class directly and have access to the sealed constructor. Derived classes cannot use that constructor via the derived constructors.
E.g.
public MyDerived() : base(string cant_access_my_sealed_constructor)
You can't do that. If the constructor is public, you can call it from constructors of derived classes. But you can do something close – you can have a private constructor and a public static method that calls it:
class MyBase
{
private MyBase(string someParam)
{
// some code
}
public static MyBase Create(string someParam)
{
return new MyBase(someParam);
}
protected MyBase() // or some other protected or public constructor
{ }
}
class MyDerived : MyBase
{
public MyDerived()
: base("foo") // won't compile, as requested
{ }
}
All constructors are "sealed" in that they cannot be "overridden." They can only be called from the constructor in a child class.
If you are hoping to prevent child classes from having a constructor with the same signature, that cannot be done.
Based on the additional information you added to the post, it sounds like what you want to do is make your constructor private, as Kyle suggested. This will prevent the child class from calling the constructor, but it won't prevent it from taking the same types of arguments:
public class Foo
{
private Foo(string s){
}
// Allowed
public Foo() : this("hello") {
}
}
public class Bar : Foo
{
// Allowed
public Bar(string s) : base(){
}
// Not allowed
public Bar(string s) : base(s){
}
}
If you want to prevent the constructor from being called by inherited classes, just mark it private.
Constructors aren't inherited by a child class, you have to explicitly call a base constructor if desired.
This code will call the base class' no-parameter constuctor when an instance of the child class is instantiated. Without it, the base class' constructor won't be called when creating a new instance of the child class.
public class A
{
public A()
{
}
}
public class B : A
{
public B()
: base()
{
}
}

C# possible to have a constructor in an abstract class?

I have 1 abstract class that is calling a static method which up until now didn't require any parameters. This has recently changed. In reality the static method exists in another class and sets the value of BaseMessageDirectory, but in this example below I have simplified things...
So now I want to create my derived classes in such a way that they can initialize some required properties in the parent class during the inheritance, is this possible?
For example....
public abstract class ParentClass
{
protected string BaseMessageDirectory;
protected ParentClass(EnumOperationType operationType)
{
if(operationtype == 1)
{
BaseMessageDirectory = "one";
}
else
{
BaseMessageDirectory = "two";
}
}
}
Yes, you can define a constructor, and all child classes will have to call it:
public class Child : ParentClass
{
public Child() : base(EnumOperationType.One) { ... }
}

Categories