Instantiate the parent class in a child class method - c#

public class Parent {}
public class Child: Parent {
public Child() {
Parent instance_of_Parent = INSERTCODEHERE;
}
}
How can I create the desired instance of the parent class in a method of the child class (not necessarily in the constructor, although that's the method I chose for brevity), without referring to "Parent" by name but instead somehow identifying it as the parent of the current class?

If you don't care about performance this will work:
public class Child: Parent {
public Child()
{
var baseClass = GetType().BaseType;
dynamic instance_of_Parent = Activator.CreateInstance(baseClass);
}
}

GetType().BaseType.GetConstructor(new Type[]{}).Invoke(null);
Thank you to DnaJur on the Rimworld Discord for this answer that allows selection of a specific constructor for the parent class to be used for the instantiation.

Related

c# Instantiate object from subclass

Below I have some simple code with a Parent Class and a Child one that extends from it.
using System;
//Base Class
public class Parent {
public void foo() {
Console.WriteLine("Parent");
}
}
//Child Class
public class Child : Parent
{
new public void foo() {
Console.WriteLine("child");
}
}
Parent parent = new Child();
parent.foo();
I'm confused as to how the two lines above work. I would've expected the compiler to bark while trying to instantiate a Parent as its own subclass. Also, why then would 'parent.foo()' still call its Parent version.
At first you shouldn't hide base class method by using new keyword you should just override it by derived class method by using virtual and override keywords. It will also fix issue that method was called from base class not from derived.
For details how it works you should read about inheritance in C#.
When you hiding method by using new keyword it always using implementation of method that is in your declared type, in your case it Parent. But if you use virtual and override it using implementation of method that is in initialized type, in your case it Child.
using System;
public class Parent
{
public virtual void foo()
{
Console.WriteLine("Parent");
}
}
public class Child : Parent
{
public override void foo()
{
Console.WriteLine("Child");
}
}
why then would 'parent.foo()' still call its Parent version?
Because you are shadowing foo by using new.
Virtual or abstract methods can be overridden by subclasses:
//Base Class
public class Parent
{
public virtual void foo()
{
Console.WriteLine("Parent");
}
}
//Child Class
public class Child : Parent
{
public override void foo()
{
Console.WriteLine("child");
}
}
I would read all of the documentation linked in the comments to decide whch will work best for your use case.

Child Class Properties Not Visible

I am fairly new to c# and very new to abstract classes. Below is an example of the code I am writing. I instantiate my object with Parent obj = new Child2(); or Parent obj = new Child3();
Note that the purpose of this is Child 2 and 3 have different properties but some common, overloaded methods.
My problem is that I can not see any properties in the child class
if I have not described the question in enough detail, please let me know and I will elaborate
namespace ns
{
public class Parent
{
public abstract DataTable ImportToDataTable()
}
public class Child2 : Parent
{
public DelimitedFileDetail InputFile = new DelimitedFileDetail();
public string PropertyforChild1 { get; set; }
public override DataTable ImportToDataTable() { .....code }
}
public class Child3 : Parent
{
public string PropertyforChild2 { get; set; }
public override DataTable ImportToDataTable() { .....code }
}
public class DelimitedFileDetail : Child2
{
public string Name { get; set; }
public ImportTypes FileType { get; set; }
public List<FieldDefinitions> FieldList = new List<FieldDefinitions>();
}
}
You should define your Parent class to be an interface instead of abstract class or base class for that matter
This way your child classes can implement the interface. Then you should use the interface variable to reference child classes/implementations.
Is there a reason you have defined Parent as abstract class? An interface should do since you haven't implemented any abstract members anyway
Well, when you declare the variable in c# with the Parent type, intelisense won't show you the properties of the child.
If you want to use the specific properties of the children you need to declare the variable with the type of the specific children.
So instead of doing:
Parent obj = new Child2();
You should do:
Child2 obj = new Child2();
And so for...
You can't see any properties of the child class because you've told the compiler that obj is of type Parent. If you want to see the properties of the child class you can cast obj to the true type:
Parent obj = new Child2();
string str = ((Child2)obj).PropertyforChild2;
This is, of course, not ideal code. Mostly because then you have to know that obj is of type Child2 and if you know that, why not just give obj the type Child2?

Create public property of internal class?

Suppose that I've this situation:
Base class or Mother class that declare this structure:
public static class Mother
{
private static Childs _child = new Childs();
public static Childs Child
{
get { return _child; }
}
}
How you can see I want implement a singleton base class for access to all methods in one place as: Mother.Child.SomeMethod.
With this structure I've a better code organization.
Now I want make the Childs class only as internal, so here start the problem 'cause I can't create a public property of an internal class. The structure of internal class is the following:
internal class Childs
{
public static bool SomeMethod() { ... }
}
so how can I make a public property of an internal class?
If the child is internal, the static access point should be internal as well.
If you actually want to have public access to some members of the child, consider using an interface.
Anyway, if there is a static access point, you don't need to make members static.
public static class Mother
{
private static Child _child = new Child();
public static IChild Child
{
get { return _child; }
}
}
public interface IChild
{
// public stuff here
bool SomeMethod();
}
internal class Child : IChild
{
public bool SomeMethod() { ... }
// additional internal members here
}
All classes in the inheritance tree must have at least the same visibility as the highest class in the hierarchy. There is no way to have a public class derive from an internal class.
Maybe your Childs class public. If you want to, you can make it abstract to prevent instantiating it or make the constructor internal to prevent deriving it in another assembly.
You cannot do that. If the property is public, any other class can access it. But if they are able to get it, they must also be able to access the class being received.

C# get caller class type (Not in Static)

How do I get the caller class type in the base?
this is the parent, here I want to print the child type without sending it
public abstract class Parent: ISomeInterface {
public void printChildType()
{
Type typeOfMyChild = ?????;
MessageBox.Show(typeOfMyChild); //how do I get Child typeOfMyChild
}
}
the child
public class Child : parent {
}
pirnt the child type :
Child child = new Child();
child.printChildType();
Thanks
(I already saw this one: Get inherited caller type name in base static class but I am using none static methods)
Type typeOfMyChild = this.GetType();
Thanks to polymorphism when you invoke:
Child child = new Child();
child.printChildType();
it should print Child.
Aren't you just looking for the current type ?
public void printChildType()
{
Type typeOfMyChild = GetType();
MessageBox.Show(typeOfMyChild);
}

how to call derived function using base class object

class Parent
{
public int GetNo()
{
return 1;
}
}
class Child : Parent
{
public Child()
{
}
public int GetNo()
{
return 2;
}
}
Parent p = new Child();
p.GetNo();
But it calls Base.GetNo(). I know if I use virutal in base it will call Child.GetNo()
But i can't use virutal in Base becuase i have to derive my class from base which is already distributed in DLL.So there's no way i can modify the existing functions of base class.
Any sugguestions are valued.
Thanks
You can cast it:
((Child)p).GetNo();
or
if(p is Child)
(p as Child).GetNo();
I have just come here so i could find a solution that doesn't use casts, but since i didn't find it here is one.
Maybe it can be of help for someone.
abstract class Parent
{
public int GetNo()
{
return GetNoImpl();
}
protected abstract int GetNoImpl();
}
class Child : Parent
{
public Child()
{
}
protected override int GetNoImpl();
{
return 2;
}
}
Parent p = new Child();
p.GetNo();
Note: the parent class is abstract.
You can force this with an explicit cast e.g.
((Child)p).GetNo();
Or you can use hiding e.g.
public new int GetNo()
{
return 2;
}
Though I think the latter only gets called if the variable is typed to the class that hides the method.
If you really need to override a method properly and it's from a compiled DLL consider getting in touch with the developers to see whether they can make the method virtual (and if not why) or if an open source project just get the source code and modify it yourself.
Without virtual declared on the method, the base method will always be called because you declared your variable as Parent. If you can't append virtual to the base class, then you can only either declare the variable as Child, or cast it to Child and call your GetNo method:
Child p = new Child();
p.GetNo();
Or:
Parent p = new Child();
((Child)p).GetNo();

Categories