Calling a base class' method - c#

In c++ I would do
class A
{
public:
virtual void stuff()
{
//something
}
};
class B : public A
public:
virtual void stuff()
{
//something2
A::stuff() //something
}
};
How would I do this in C#?
I've tried
public void stuff()
{
//something2
A.stuff(); //something
}
but that doesn't work

base is the keyword for referencing your superclass in C#. Use:
base.stuff();

Use base. Like base.stuff();

Just to add to the answer above, base.stuff() works, unless it's the constructor you're trying to call in which case it is called as:
class A
{
public:
public A(){}
};
class B : A
{
public B() : base()
{
}
};

Related

Multiple inheritance using interaces

Please consider the attached figure.
What I want is that the (technical-) "User" can use methods from class A, B or C by an instantiate of "HeadClass". What I try to avoid is, that I have to add a separate function for each method defined in Class A, B and C to call them through the "HeadClass". I tried to describe this in an other stackoverflow-request yesterday but have deleted it because it seemed to be unclear what I wanted to achieve. So here is an other approach.
Usually this would be achieved by inheritance (if only one class would be inherited from). But, as they told me in that deleted post, I should use Interface instead. Now, so far I thought that I know how interface work (using almost for every class), but I can't figure how I achieve this describe problem.
How would I have to fill the "???" in "HeadClass"?
I am happy for any input. Thx in adavnce!
class User
{
public User(IHeadClass headObj)
{
_headObj = headObj
}
public DoStuff()
{
_headObj.Method_1
_headObj.Method_2
_headObj.HeadMethod
}
}
public class HeadClass : IHeadClass, ???
{
???
public HeadClass( ??? )
{
???
}
void HeadMethod()
{
... do head stuff
}
}
public class Class_A : IClass_A
{
public void Method_1 () { }
}
public class Class_B : IClass_B
{
public void Method_2 () { }
public void Method_3 () { }
}
public class Class_C : IClass_C
{
public void Method_4 () { }
}
I have check out this describing how to use interfaces instead. But this doesn't solve the above problem.
If I understand correctly you can use composition here. Something like this:
public interface IClass_A
{
void Method_1 ();
}
public interface IClass_B
{
void Method_2 ();
void Method_3 ();
}
public interface IClass_C
{
void Method_4 ();
}
public interface IHeadClass : IClass_A, IClass_B, IClass_C
{
void HeadMethod();
}
public class HeadClass : IHeadClass
{
private readonly IClass_A _a;
private readonly IClass_B _b;
private readonly IClass_C _c;
public HeadClass(IClass_A a, IClass_B b, IClass_C c)
{
_a = a;
_b = b;
_c = c;
}
void HeadMethod()
{
... do head stuff
}
public void Method_1() => _a.Method_1();
public void Method_2() => _b.Method_2();
public void Method_3() => _b.Method_3();
public void Method_4() => _c.Method_4();
}
C# (unlike for example C++ or PHP) does not support multiple inheritance. Interfaces allows multiple inheritance, but they don't provide definitions of methods, only declarations.
I think solution could be pattern called fasade: write methods in HeadClass that calls methods in other classes. In this case interfaces are not necessary.
public class HeadClass
{
private Class_A _a;
private Class_B _b;
private Class_C _c;
public HeadClass( Class_A a, Class_B b, Class_C c )
{
_a=a;
_b=b;
_c=c;
}
void HeadMethod()
{
... do head stuff
}
public void Method_1 () {
_a.Method_1();
}
public void Method_2 () {
_b.Method_2();
}
public void Method_3 () {
_b.Method_3();
}
public void Method_4 () {
_c.Method_4();
}
}
May I suggest instead that you have an interface passed instead of Class definition in your constructor?
public class HeadClass
{
private IMethod1 _method1;
private IMethod2 _method2;
private IMethod3 _method3;
private IMethod4 _method4;
public HeadClass( IMethod1 method1, IMethod2 method2, IMethod3 method3, IMethod4 method4)
{
_method1=method1;
_method2=method2;
_method3=method3;
_method4=method4;
}
void HeadMethod()
{
... do head stuff
}
public void Method_1 () {
_method1.Method_1();
}
public void Method_2 () {
IMethod2.Method_2();
}
public void Method_3 () {
IMethod3.Method_3();
}
public void Method_4 () {
IMethod4.Method_4();
}
}
Now you have removed any direct coupling to a class, you are no only linked by interface.
Say you want to split method 2 and 3 into it's own two classes? this code, never has to change.
You can now reuse any class that has a definition of the interface, as a paramater. No code is defined twice, that does the same thing, in each input.
Because:
public class Method1 : IMethod1
{
}
public class Method2 : IMethod2
{
}
public class Method3 : IMethod3
{
}
public class Method4 : IMethod4
{
}
can now be parsed as parameters to HeadClass.
or, if you insist method 2 & 3 belong on the same class.
public class ClassA: IMethod1
{
}
public class ClassB: IMethod2, IMethod3
{
}
public class ClassC: IMethod4
{
}
Should be obvious from this example that the benefits lie in the fact that you can now do whatever you want in Headclass, and if you need behaviour to change, you can inject code via constructor, without having to retry the behaviour of headclass.
And headclass, doesn't know ClassA, B or C exist directly, only the interface.
I Believe this is called the Strategy pattern?

How to access the first base class in C#?

I'm having a base class defined in my app
Something like,
using System;
public class BaseClass
{
public virtual void Method2() {Console.WriteLine("base2");}
public virtual void Method1() {Console.WriteLine("base1");}
}
public class Derived1 : BaseClass
{
public override void Method2() {Console.WriteLine("derived1-2");}
public override void Method1() {Console.WriteLine("derived1-1");}
}
public class Derived2 : Derived1
{
public override void Method1() {Console.WriteLine("derived2-2");}
}
public class Program
{
public static void Main()
{
var obj = new Derived2();
((BaseClass)obj).Method2();
Console.WriteLine("Hello World");
}
}
Say I need to access the Method2() of my very first BaseClass. Even after typecasting it to ((BaseClass)obj).Method2(), I'm still getting derived1-2 while I'm expecting base2'.
How do I do that ?
I completely agree with the comments: it sounds like the behaviour that you require would need you to re-think your classes - possibly inheritance is not the best solution in this case. It depends what you're trying to do; you could obviously just do this:
var obj = new BaseClass();
((BaseClass)obj).Method2();
Console.WriteLine("Hello World");
My guess would be that what you actually want here is some form of injection; for example:
public class BaseClass
{
private readonly IFunctionality1 functionality1;
public virtual void Method2() { Console.WriteLine("base2"); }
public virtual void Method1() { this.functionality1.Method1(); }
public BaseClass(IFunctionality1 functionality1)
{
this.functionality1 = functionality1;
}
}
public class Derived1 : BaseClass
{
public Derived1(IFunctionality1 functionality1) : base (functionality1)
{
}
}
In this case, you might find that inheritance isn't even required anymore.

How can I make sure that a method of class can be called from a specific class only?

public class A
{
private void MethodA(){}
}
public class B
{
private void MethodB() { }
}
public class C
{
private void MethodC() { }
}
I want to make sure that MethodA can be called only from MethodB. Other method can never call MethodA.
Make MethodA protected and use inheritance like this:
public class A
{
protected void MethodA()
{
}
}
public class B : A
{
private void MethodB()
{
//MethodA is accessible just here
}
}
public class C
{
private void MethodC()
{
//MethodA is not accessible here
}
}
But if you don't want to use inheritance and want all the classes in the same assembly you could only nest class B within class A and keep MethodA private. Like this:
public class A
{
private void MethodA()
{
}
public class B
{
private void MethodB()
{
A a = new A();
a.MethodA();
}
}
}
public class C
{
private void MethodC()
{
//MethodA is not accessible here
}
}
public class D : A
{
private void MethodC()
{
//MethodA is not accessible here
}
}
I note that S.Akbari's answer, though good, does not exactly meet your requirement. You said that you wanted MethodA to be callable only within B, but in their answer, MethodA is callable within A.
The solution to the problem you actually posed is to invert the nesting:
class B
{
private class A
{
public void MethodA() { }
}
}
Now MethodA can only be called from within B.
But the question is bizarre. If you have a method that can only be called from B then why is it not a member of B?

How to refactor the following code without killing OOPS in C#

I have 3 interfaces with 2 methods each doing the same job.
Interface A
{
Void M1()
Void M2()
}
Interface B
{
Void M1()
Void M2()
}
Interface C
{
Void M1()
Void M2()
}
Now, There are 3 classes implementing each of these interfaces.
Public Class A1:A
{
Public void M1()
{
}
Public void M2()
{
}
}
Public Class B1:B
{
Public void M1()
{
}
Public void M2()
{
}
}
Public Class C1:C
{
Public void M1()
{
}
Public void M2()
{
}
}
Functionality of M1 and M2 is exactly same in 3 classes. Interfaces are a part of library, I cannot change the interface and also cannot declare a new interface.
I want to refactor this code so that this duplication can be removed. I thought of creating a common class containing this functionality and then calling common class from each of these classes.
Please suggest.
It sounds like you should declare your own interface, and then create an adapter - or possibly multiple adapters. For example:
public interface IUnified
{
void M1();
void M2();
}
public class UnifiedAdapter : IUnified
{
private Action m1;
private Action m2;
public UnifiedAdapter(A a)
{
m1 = () => a.M1();
m2 = () => a.M2();
}
public UnifiedAdapter(B b)
{
m1 = () => b.M1();
m2 = () => b.M2();
}
public UnifiedAdapter(C c)
{
m1 = () => c.M1();
m2 = () => c.M2();
}
public M1()
{
m1();
}
public M2()
{
m2();
}
}
(This uses delegates to avoid having to create multiple adapter classes. The best approach depends on your exact situation.)
public abstract class XX : X
{
public void M1()
{
}
public void M2()
{
}
}
public interface X : A, B, C
{
}
Given the odd restrictions (and if you can I really suggest trying to get the interfaces changed) I think this is the best you can do:
public class Base : A, B, C {
public void M1(){}
public void M2(){}
}
Now inherit from Base in A1, B1 and C1.
However, if an A cannot, or should not, also be a B then this pattern won't work.
Therefore you would indeed have to go for the next best thing - a common base with the common functionality:
public class Base {
protected void M1Impl() { /* put your common implementation in here */ }
protected void M2Impl() { /* put your common implementation in here */ }
}
As the comments say - put the duplicated M1 and M2 code in the M1Impl and M2Impl methods here.
Now you can reuse this base for A, B and C implementations:
//common base for any implementation of A
//repeat for B and C
public class A1Base : Base, A
{
public void M1() { M1Impl(); }
public void M2() { M2Impl(); }
}
public class A1 : A1Base { }
I've worked on the basis here that you might have many implementations of A or B or whatever, and therefore you want a common starting point for each of those. If that's not the case, then you can do away with A1Base and simply call it A1.
public class BaseClass : A, B, C
{
public void M1()
{
}
public void M2()
{
}
}
Then just inherit from BaseClass:
public class A1 : BaseClass
{
}
public class B1 : BaseClass
{
}
public class C1 : BaseClass
{
}
A1 still will implement interface A. B1 will implement interface B. Same with C1. So, all your existing code will remain working:
A a = new A1();
a.M1();
If you only want to avoid to duplicate the implementation of those methods, then your initial approach is correct.
public class HelperClass
{
public static void M1()
{
// implementation code
}
public static void M2()
{
// implementation code
}
}
public class A1:A
{
public void M1()
{
HelperClass.M1();
}
public void M2()
{
HelperClass.M2();
}
}
public class B1:B
{
public void M1()
{
HelperClass.M1();
}
public void M2()
{
HelperClass.M2();
}
}
public class C1:C
{
public void M1()
{
HelperClass.M1();
}
public void M2()
{
HelperClass.M2();
}
}
Even if interfaces A, B, and C have the same methods, they may have different semantics and may make sense to have them as separate interfaces. That is, making a class implement A, may mean something different than implementing B, even if their methods have the same signatures.
Adding additional interfaces or common base classes is overkill and adds unneeded coupling. As I said before, if you only need to avoid duplicating the methods' implementation, a helper class is the easiest and cleanest solution.

Call Constructor Base after Code Execution

Let say we have Class A and Class B. ClassB extends Class A. (ClassB : ClassA)
Now let's say that whenever I instantiate ClassB, I'd like to Run some Random code and only then call "base" to reach ClassA constructor.
Like:
class ClassA
{
public ClassA()
{
Console.WriteLine("Initialization");
}
}
class ClassB : ClassA
{
public ClassB() //: base()
{
// Using :base() as commented above, I would execute ClassA ctor before // Console.WriteLine as it is below this line...
Console.WriteLine("Before new");
//base() //Calls ClassA constructor using inheritance
//Run some more Codes here...
}
}
In the programming language I usually work with, I can do that, by simply calling super() after Console.WriteLine(); But I cant make it in C#. Is there any other syntax or other way to do that?
There's a hacky way of doing it using an instance variable initializer:
using System;
class ClassA
{
public ClassA()
{
Console.WriteLine("Initialization");
}
}
class ClassB : ClassA
{
private readonly int ignoreMe = BeforeBaseConstructorCall();
public ClassB()
{
}
private static int BeforeBaseConstructorCall()
{
Console.WriteLine("Before new");
return 0; // We really don't care
}
}
class Test
{
static void Main()
{
new ClassB();
}
}
The less hacky way of doing it is to rethink how you construct a ClassB to start with. Instead of having clients call the constructor directly, provide a static method for them to call:
public static ClassB CreateInstance()
{
Console.WriteLine("Before initialization stuff");
return new ClassB();
}
Another hack if you can get away with calling a static method.
public class ClassA
{
public ClassA()
{
Debug.WriteLine("Call A Constructor");
}
}
public class ClassB:ClassA
{
public ClassB():this(aMethod())
{
}
private ClassB(object empty):base()
{
Debug.WriteLine("Class B Second Constructor");
}
private static object aMethod()
{
Debug.WriteLine("Run me First");
return null;
}
}
Another elegant solution would be to completely rethink how your objects are constructed. In the constructor of your base class you can call your own construct function, and you omit dependent future constructors, in the following way:
public class ClassA
{
public ClassA()
{
Construct();
}
public virtual void Construct()
{
Console.WriteLine("3");
}
}
public class ClassB : ClassA
{
public override void Construct()
{
Console.WriteLine("2");
base.Construct();
}
}
public class ClassC : ClassB
{
public override void Construct()
{
Console.WriteLine("1");
base.Construct();
}
}
Actually, you can:
class Foo
{
public Foo(string s)
{
Console.WriteLine("inside foo");
Console.WriteLine("foo" + s);
}
}
class Bar : Foo
{
public Bar(string s) : base(((Func<string>)(delegate ()
{
Console.WriteLine("before foo");
return "bar" + s;
}))())
{
Console.WriteLine("inside bar");
}
}
class Program
{
static void Main(string[] args)
{
new Bar("baz");
}
}
Output:
before foo
inside foo
foobarbaz
inside bar
But I will prefer to not use this trick if it is possible.
C# doesn't allow calling base constructors inside constructor bodies, different from Java.
You can't do that with C#. Your best bet is to extract that code into it's own method in the parent and then call that from the child when you're ready.
I am surprised noone has suggested using an abstract method - though it does rely on the base being implemented as an abstract class which wont work for all cases (although you could simply fork the inheritance and stack the non-abstract on top if yu have to). This has the advantage of ensuring the integrity of your code without resorting to hackiness. Because we are using abstract, it is not possible to instantiate the derived class without declaring initCode.
using System;
abstract class ClassA
{
internal abstract initCode();
public ClassA()
{
initCode();
Console.WriteLine("Initialization");
}
}
class ClassB : ClassA
{
public ClassB()
{
}
internal override initCode()
{
Console.WriteLine("Before new");
return 0; // We really don't care
}
}
//If you need to effectively get the non-abstract of ClassA
class ClassC : ClassA
{
public ClassB()
{
}
internal override initCode()
{
}
}
You can not call base constructor.
But a different thing is that when you declare an object of derived class both constructor derived and base is called.
class ClassA
{
public ClassA()
{
Console.WriteLine("Initialization");
}
}
class ClassB : ClassA
{
public ClassB() //: base()
{
// Using :base() as commented above, I would execute ClassA ctor before // Console.WriteLine as it is below this line...
Console.WriteLine("Before new");
//base() //Calls ClassA constructor using inheritance
//Run some more Codes here...
}
}
void main(string[] args)
{
ClassB b = new ClassB();
}
Recently I ran into a scenario where I needed to calculate some logic before passing the result into base.
I could just do something like
public SomeConstructor: base(FlagValue == FlagValues.One || FlagValues.Two ? "OptionA" : "OptionB")
{
}
But I find that to be ugly, and can get really long horizontally. So I opted instead to use Func Anonymous methods.
E.g. imagine you have a base class,
public class SomeBaseClass
{
public SomeBaseClass(Func<string> GetSqlQueryText){
string sqlQueryText = GetSqlQueryText();
//Initialize(sqlQueryText);
}
}
Now you inherit from that and want to do some logic to determine the sql query text,
public class SomeSqlObject : SomeBaseClass
{
public SomeSqlObject(ArchiveTypeValues archiveType)
: base(delegate()
{
switch (archiveType)
{
case ArchiveTypeValues.CurrentIssues:
case ArchiveTypeValues.Archived:
return Queries.ProductQueries.ProductQueryActive;
case ArchiveTypeValues.AllIssues:
return string.Format(Queries.ProductQueries.ProductQueryActiveOther, (int)archiveType);
default:
throw new InvalidOperationException("Unknown archiveType");
};
})
{
//Derived Constructor code here!
}
}
In this way you can execute code before Base is called and (in my opinion) it's not really hacky.
I had the same problem. I found this solution to be the best if you don't have access to the base class.
public class BaseClass
{
public BaseClass(string someValue)
{
Console.WriteLine(someValue);
}
}
public class MyClass : BaseClass
{
private MyClass(string someValue)
: base(someValue)
{
}
public static MyClass GetNewInstance(string someValue, bool overrideValue = false)
{
if (overrideValue)
{
someValue = "42";
}
return new MyClass(someValue);
}
}

Categories

Resources