Can I inherit from an instantiated class? - c#

I'm trying to inherit from an instantiated class. Why is the value of Inherited, in the code below, a null value? Is there a way to do this correctly?
namespace Sample {
public class Class1 {
static void Main() {
Class2 SecondClass = new Class2();
SecondClass.StartSomething("hello world");
}
}
public class Class2 {
public string Inherited;
public void StartSomething(string value) {
Inherited = value;
InheritSomething();
}
public void InheritSomething() {
Class3 ThirdClass = new Class3();
ThirdClass.DoSomething();
}
}
public class Class3 : Class2 {
public void DoSomething() {
Console.WriteLine(Inherited);//when complied Inherited is null
Console.ReadLine();
}
}
}

Inheriting occurs at compile time. (Therefore 'Inherited' does not have a value yet)
Values are assigned at run-time.

Inheriting from a class does not inherit the INSTANCE of that class at instantiation of the inherited class. Instead, you'd need to pass along the instance of that class. One option is to inject it into the constructor of class 3
public class Class1
{
static void Main()
{
Class2 SecondClass = new Class2();
SecondClass.StartSomething("hello world");
}
}
public class Class2
{
public string Inherited;
public void StartSomething(string value)
{
Inherited = value;
InheritSomething();
}
public void InheritSomething()
{
Class3 thirdClass = new Class3(this);
thirdClass.DoSomething();
}
}
public class Class3 : Class2
{
private Class2 _class2;
public Class3(Class2 class2)
{
_class2 = class2;
}
public void DoSomething()
{
Console.WriteLine(_class2.Inherited);
Console.ReadLine();
}
}

Related

Two projects, a derived class should be able to access one method but not the other one

I was asked this question in interview, but couldn't answer it.
There are two projects: P1 and P2
P1 has a class A with methods M1 and M2
P2 has a class B and class C, both of these classes (inherit or reference)* from class A in Project P1
Class B should be able to access method M1 but not M2
Class C should be able to access method M2 but not M1
*I don't remember if he said inherit or said reference
How can this be done?
You want to use interfaces to extract methods from class.
P1:
public interface IM1
{
void M1();
}
public interface IM2
{
void M2();
}
// Not public
internal class A : IM1, IM2
{
public void M1() {}
public void M2() {}
}
P2:
public class B
{
private readonly IM1 _m1;
}
public class C
{
private readonly IM2 _m2;
}
You can implement some like: https://dotnetfiddle.net/0mYxdU
public interface InterfaceCommon
{
void Function();
}
public class Implementacion1 : InterfaceCommon
{
public void Function()
{
Console.WriteLine("I am Method1");
}
}
public class Implementacion2 : InterfaceCommon
{
public void Function()
{
Console.WriteLine("I am Method2");
}
}
public abstract class A
{
private readonly InterfaceCommon interfaceCommon;
protected A(InterfaceCommon interfaceCommon)
{
this.interfaceCommon = interfaceCommon;
}
public void CallFunction()
{
interfaceCommon.Function();
}
}
public class B : A
{
public B() : base(new Implementacion1()) { }
}
public class C : A
{
public C() : base(new Implementacion2()) { }
}
public class Program
{
public static void Main(string[] args)
{
var b = new B();
b.CallFunction();
var c = new C();
c.CallFunction();
Console.ReadLine();
}
}

How to Access method in Parent from Child Class

I have one method which is in child class and I want to fetch that in Parent with the help of this.
public class Class1
{
private class Class2
{
public void Add(int a, int b) // Method in Class 2
{
this.Add(a, b);
}
}
public Class1() // constructor of Class 1
{
// Get this Add method by This.Add ??
// Not able to fetch the Add method here.
}
}
you have declared the method but it is in class2. that means you need to create an instance of class2 in order to use the method
public class Class1
{
private class Class2
{
public void Add(int a, int b) // Method in Class 2
{
this.Add(a, b);
}
}
public Class1() // constructor of Class 1
{
class2 cs = new class2();
cs.Add(4,5);
}
}
You would either have to create an instance of Class2 in the constructor of Class1 and use an instance method, or change the method Add to static in Class2
Static version
Something like
public class Class1
{
private class Class2
{
public static void Add(int a, int b)
{
}
}
public Class1()
{
Class2.Add(1,2);
}
}
Instance version
Something like
public class Class1
{
private class Class2
{
public void Add(int a, int b)
{
}
}
public Class1()
{
new Class2().Add(1,2);
}
}
Maybe have a look at static (C# Reference)
public class Class1
{
private class Class2
{
public void Add(int a, int b) // Method in Class 2
{
this.Add(a, b);
}
}
public Class1() // constructor of Class 1
{
Class2 newclass2 = new Class2();
newclass2.Add(1, 2);
// Get this Add method by This.Add ??
// Not able to fetch the Add method here.
}
}
You need to create instance for Class2
public class Class1
{
private class Class2
{
public Class2() // constructor of Class2
{
}
public void Add(int a, int b) // Method in Class2
{
this.Add(a, b);
}
}
public Class1() // constructor of Class1
{
Class2 cs2 = new Class2();
cs2.Add(4,5);
}
}

adding methods from class A to a delegate of class B and calling that delegate from class A in C#

How can I add a method from class A to a delegate of class B without knowing in advance which method I will be adding and what class A is? And then call that delegate from class A?
class Class {
public string someProperty;
public delegate void myDelegate(Class obj);
myDelegate handler = new myDelegate(mainClassMethod); //here is the problem..
public void someMethod() {
handler();
}
}
class MainClass {
public static void Main() {
Class classObj = new Class();
classObj.someProperty = "hello";
public void mainClassMethod(Class obj) {
System.Console.WriteLine(obj.someProperty);
}
classObj.someMethod();
}
}
Should I use something other than delegates for this? By the way I am doing this in C#!
make mainClassMethod static and access it via class name MainClass. Also you cant declare nested functions as class members, you need to declare mainClassMethod separately.
class MainClass {
public static void Main()
{
Class classObj = new Class();
classObj.someProperty = "hello";
classObj.someMethod();
}
public static void mainClassMethod(Class obj)
{
System.Console.WriteLine(obj.someProperty);
}
}
Also you declared delegate void myDelegate(Class obj); so you need to pass instance of a Class as a parameter. In my example I pass object found by this reference, which is an object that you call someMethod at.
Now you can write:
class Class {
public string someProperty;
public delegate void myDelegate(Class obj);
myDelegate handler = new myDelegate(MainClass.mainClassMethod); //no error
public void someMethod()
{
handler(this);
}
}

Keep track of total amount of instances created for class and subclass

Note: This is a homework assignment.
I have two classes, one inherits from the other. The assignment tells us to make the classes able to keep track of the total amount of instances created of each class.
class FirstClass
{
private static int _instancesCreated = 0;
public FirstClass()
{
_instancesCreated++;
}
}
That piece of code works well as far as I know. The problem is that I have a subclass which has to call the constructor of it's parent class.
class SecondClass:FirstClass
{
public SecondClass() : base()
{
}
}
So now the problem becomes how to properly separate the two. Since I have to call the parent constructor the _instancesCreated for that class will become incorrect, although I suppose it's true in a sense...?
Thanks for your help
The easiest way is to make _instancesCreated protected, and then decrement it in each of your subclasses constructors. That's how you make _instancesCreated store only the number of base class instances. For counting subclasses instances you should add static fields for each of them, and increment them in constructors, just like you did in your base class.
class SecondClass:FirstClass
{
private static int _sub_instancesCreated = 0;
public SecondClass() : base()
{
_sub_instancesCreated ++;
}
}
separately
class FirstClass
{
private static int _instancesCreated = 0;
public FirstClass()
{
_instancesCreated++;
}
protected FirstClass(int i)
{
}
}
class SecondClass:FirstClass
{
private static int _sub_instancesCreated = 0;
public SecondClass() : base(2) //dummy
{
_sub_instancesCreated ++;
}
}
A more general solution (if a bit overkill):
using System;
using System.Collections.Generic;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
new BaseClass();
new BaseClass();
new DerivedClass();
Console.WriteLine("Base classes: {0}, Derived classes: {1}",
BaseClass.CountInstances<BaseClass>(),
BaseClass.CountInstances<DerivedClass>());
}
}
public class BaseClass
{
public static Dictionary<Type, int> InstanceCount =
new Dictionary<Type, int>();
public static int CountInstances<T>() where T : BaseClass
{
return BaseClass.InstanceCount.ContainsKey(typeof(T)) ? BaseClass.InstanceCount[typeof(T)] : 0;
}
public BaseClass()
{
if (!InstanceCount.ContainsKey(this.GetType()))
{
InstanceCount[this.GetType()] = 0;
}
InstanceCount[this.GetType()]++;
}
}
public class DerivedClass : BaseClass
{
public DerivedClass()
: base()
{
}
}
}

How to access functions from abstract class without making them static?

I want to create a class that can only be inherited, for that i know it should be made abstract. But now the problem is that i want to use functions of that class without making them static. How can i do that.
public abstract Class A
{
A()
{}
public void display()
{}
}
public Class B:A
{
base.A() // this is accessible
this.display() // this is not accessible if i dont make this function static above
}
Your example will not compile, you could consider something like this:
using System;
public abstract class A
{
protected A()
{
Console.WriteLine("Constructor A() called");
}
public void Display()
{
Console.WriteLine("A.Display() called");
}
}
public class B:A
{
public void UseDisplay()
{
Display();
}
}
public class Program
{
static void Main()
{
B b = new B();
b.UseDisplay();
Console.ReadLine();
}
}
Output:
Constructor A() called
A.Display() called
Note: Creating a new B() implicitly calls A(); I had to make the constructor of A protected to prevent this error:
"'A.A()' is inaccessible due to its protection level"
That's not true. You don't have to make Display() static; you can call it freely from the subclass. On the other hand, you can't call the constructor like that.
Maybe it's just an error in the example, but the real issue with the code you have is that you can't put method calls in the middle of your class definition.
Try this:
public abstract class A
{
public void Display(){}
}
public class B:A
{
public void SomethingThatCallsDisplay()
{
Display();
}
}
Here's how you can do this..
public abstract class A
{
public virtual void display() { }
}
public class B : A
{
public override void display()
{
base.display();
}
public void someothermethod()
{
this.display();
}
}

Categories