Inherited class references base class' values - c#

public class ParentClass
{
public int myId;
public string commonField1;
public string commonField2;
public string commonField3;
public string changeable;
public List<ChildClass> children;
public ParentClass(int id)
{
myId = myId;
}
public createChildren()
{
for(int i = 0; i < 999999; i++)
{
children.Add(new ChildClass(id));
}
}
}
public class ChildClass : ParentClass
{
public ChildClass(int id) : base (id)
{
myId = myId;
changeable = "new";
}
}
Because ChildClass only exists in the context of it's ParentClass, and there will be 999999 children. That is creating 999999 copies of all the commonField's when in reality it just needs a reference to it's parent. The only real thing a ChildClass needs to store besides references is changeable.
How can this be accomplished?
I am almost thinking a better approach when I need the children is just to make 999999 shallow copies of the ParentClass and just change the 999999 changeable fields. Shallow copies will have references to commonField1 or would it deep copy values?

You have one thing right, thats a lot of repeated data if commonFieldX is truly unchanging.
I see several solutions:
Prefer Composition over Inheritance
Why are you inheriting at all? If there is no polymorphic behavior, then just pass the base class instance to the 10000 children and call it good:
public createChildren()
{
for(int i = 0; i < 999999; i++) {
children.Add(new ChildClass(id, this));
}
}
public class ChildClass
{
public ChildClass(int id, ParentClass parent) : base (id)
{
myId = myId; //This shouldn't be part of the base class?
changeable = "new"; //Same here
myParent = parent;
}
}
Share those variables among all instances
static members belong to the "global" instance, so they won't be recreated for each derived object:
public class ParentClass
{
public int MyId {get; set;}
public static string CommonField1 {get; set;}
public static string CommonField2 {get; set;}
public static string CommonField3 {get; set;}
public string Changeable {get; set;}
Note that some of this should likely be protected instead of public and you should always expose public fields via properties instead of directly. Of course, if you have multiple instances of ParentClass that have differing values of those fields, this is a no-go.

If child and parent should have some relation (i.e. common parent class to share methods/properties), but child need to share properties with parent you can redirect properties request to parent (note that it would men getting property of deeply nested child is very slow):
public class Node
{
public virtual string Field {get {return parent != null ? parent.Field : field;}}
public Node parent;
public List<Node> children;
public Node()
{
children = new List<Node>();
}
public createChildren()
{
for(int i = 0; i < 999999; i++)
{
children.Add(new ChildNode(i, this));
}
}
}
public class ChildNode : Node
{
public override string Field {get {return parent.Field;}}
public ChildNode(Node parent)
{
this.parent = parent;
}
}
public class RootNode : Node
{
public override string Field {get {return "Root";}}
public RootNode()
{
this.parent = null;
}
}

Related

Decoupling Pattern

After looking at major pattern designs, I can't seem to make up my mind around the best to one to decouple classes in a big hierarchy system, specially were it concerns on avoiding injecting a Parent property in EVERY object along the way.
Some of the premises are:
A child might me removed from one parent and added to another.
Somewhere down the hierarchy, I need to access Parent of type X.
As mentioned before, I would like to avoid injecting a Parent (either by property or constructor) to it's children.
I have 1..1 and 1...N cardinalities.
The hierarchy from root to furthest leaf is quite extent.
If it was a small project, I would be fine with this (pseudo code):
public abstract class BaseObject()
{
public BaseObject Parent { get; set; }
}
public class RootObject() : BaseObject
{
public int Id { get; }
public ParentObject[] Parent { get; set; }
}
public class ParentObject() : BaseObject
{
public int Id { get; }
public ChildObject[] Parent { get; set; }
}
public class ChildObject() : BaseObject
{
public int Id { get; }
public void DoSomething()
{
//...navigate through Parent to get RootObject (or any other type in between that I might need)...
}
}
Can anyone point me out to the right direction?
All these requirements remind me graph data structure:
A child might me removed from one parent and added to another.
Somewhere down the hierarchy, I need to access Parent of type X.
As mentioned before, I would like to avoid injecting a Parent (either by property or constructor) to it's children.
I have 1..1 and 1...N cardinalities.
The hierarchy from root to furthest leaf is quite extent.
The easiest storage would be List<Node> where each node contains links to its predecessors and successors:
class Example
{
public List<Node> InitGraph()
{
var nodes = new Dictionary<string, Node>();
nodes.Add("Head", new Node("Head"));
nodes.Add("T1", new Node("T1"));
nodes.Add("T2", new Node("T2"));
// While that works, a method is nicer:
nodes.Add("C1");
// These two lines should really be factored out to a single method call
nodes["Head"].Successors.Add(nodes["T1"]);
nodes["T1"].Predecessors.Add(nodes["Head"]);
nodes["Head"].Successors.Add(nodes["T2"]);
nodes["T2"].Predecessors.Add(nodes["Head"]);
// Yes. Much nicer
nodes.Connect("Head", "C1");
nodes.Connect("T1", "C1");
nodes.Connect("T2", "C1");
var nodelist = new List<Node>(nodes.Values);
return nodelist;
}
}
and NodeHelper class:
public static class NodeHelper
{
public static void Add(this Dictionary<string, Node> dict, string nodename)
{
dict.Add(nodename, new Node(nodename));
}
public static void Connect(this Dictionary<string, Node> dict, string from, string to)
{
dict[ from ].Successors.Add(dict[ to ]);
dict[ to ].Predecessors.Add(dict[ from ]);
}
}
and Node class:
public class Node
{
public string Name { get; set; }
public int Coolness { get; set; }
public List<Node> Predecessors { get; set; }
public List<Node> Successors { get; set; }
public Node()
{
Coolness = 1;
}
public Node(string name) : this()
{
this.Name = name;
}
}

Proper use of Ninject NamedScope

I´m having a hard time trying to understand how Ninject´s NamedScope module should work. In my mind, each (defined)scope should be used to contextualize bindings that are "InNamedScope".
With this toy example:
void Main()
{
var kernel = new StandardKernel(new NamedScopeModule(), new ContextPreservationModule());
kernel.Bind<ParentC>().ToSelf().WithConstructorArgument("name", "Name1").DefinesNamedScope("scope1");
kernel.Bind<Intf>().ToConstant(new MyC() { ID = 1} ).InNamedScope("scope1");
kernel.Bind<ParentC>().ToSelf().WithConstructorArgument("name", "Name2").DefinesNamedScope("scope2");
kernel.Bind<Intf>().ToConstant(new MyC() { ID = 2 }).InNamedScope("scope2");
kernel.GetAll<ParentC>().Dump();
}
public class Intf
{
int ID { get; set; }
}
public class MyC : Intf
{
public int ID { get; set; }
}
public class ParentC
{
public ParentC(Intf[] c, string name)
{
this.C = c;
Name = name;
}
public string Name { get; set; }
public Intf[] C { get; set; }
}
for me, should yield something like this:
But instead, I get an exeception:
UnknownScopeException: Error activating UserQuery+Intf
The scope scope2 is not known in the current context.
what am I missing ?
In Ninject, scope is related to lifetime of objects. I see named scope more as a way of injecting the same instance into different classes, like this:
public class Parent {
public Parent(Child child, GrandChild grandChild) {}
}
public class Child {
public Child(GrandChild grandchild) {}
}
public class GrandChild {}
kernel.Bind<Parent>().ToSelf().DefinesNamedScope("scope");
kernel.Bind<GrandChild>().ToSelf().InNamedScope("scope");
kernel.Get<Parent>();
The grandChild injected into Parent is the same instance as is injected into Child.

Set default properties in base class from derived class

Ok so, I've run into an interested and probably simple problem. I have a base class that is inherited by another class (child). I have the same parameterless constructor in the base and the child. I would like to set defaults in the child that propagate into the base properties. I would like to do something like this:
public partial class baseclass
{
public baseclass() {
//never called if instantiated from baseclass(string newp1)
p1 = "";
p2 = "google";
}
public baseclass(string newp1) {
p1 = newp1; //p2 will be "" and p1 will be newP1
}
public string p1 { get; set; }
public string p2 { get; set; }
}
public partial class childclass : baseclass
{
public childclass() {
//How can I call this to set some default values for the child?
p2 = "facebook";
}
public childclass(string newp1) : base(newp1) {
p1 = newp1; //p2 needs to be "facebook"
}
}
Use constructors chaining if you have duplicated code in several constructors:
public class baseclass
{
public baseclass() : this("google") { }
public baseclass(string newp1)
{
p1 = newp1; // the only place in your code where you init properties
p2 = "";
}
public string p1 { get; set; }
public string p2 { get; set; }
}
Child class should inherit baseClass
public class childclass : baseclass
{
public childclass() : this("facebook") { } // you can also call base here
public childclass(string newp1) : base(newp1) { }
}
Also keep in mind that parital just allows you split class/method definiton in several parts (e.g. keep it in different files). It is useful when you are generating classes (e.g. from database tables) but still want to add/customize something in generated classes. If you will put customized code directly into generated files, then it will be lost after classes re-generation. Read more
You can create a protected constructor in base class and call it in child class:
public class Base
{
public Base(int value1, int value2) { ... }
protected Base(string value1) { ... } // only for child class
}
public class Child : Base
{
public Child() : Base("Value") { ... }
}

Copying base class in derived class constructor

Is there a way to copy an object fields to a base class in a derived class constructor without having to individually copying every field?
Example:
public class A
{
int prop1 { get; set; }
int prop2 { get; set; }
}
public class B : A
{
public B(A a)
{
//base = a; doesn't work.
base.prop1 = a.prop1;
base.prop2 = a.prop2;
}
}
A a = new A();
B b = new B(a);
public class A
{
public A(A a)
{
prop1 = a.prop1;
prop2 = a.prop2;
}
int prop1 { get; set; }
int prop2 { get; set; }
}
public class B : A
{
public B(A a) : base (a)
{
}
}
A a = new A();
B b = new B(a);
Something like this, although I'm not sure if it is syntactically correct because I didn't compile it. You should use the base keyword after the child class's constructor to pass the values of it's dependencies to the base class.
Edit: But I just realized that you are passing a base class to a child class. And this is a design flaw.
It sounds like you want to add all properties from A to B without having to specify them all separately. If you don't want to have to keep adding new ones to the constructor, you could use reflection to do the work for you.
public B(A a)
{
var bType = this.GetType();
// specify that we're only interested in public properties
var aProps = a.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
// iterate through all the public properties in A
foreach (var prop in aProps)
{
// for each A property, set the same B property to its value
bType.GetProperty(prop.Name).SetValue(this, prop.GetValue(a));
}
}
A few notes about this:
The above code sets public instance properties, so you'd need to change your properties in A to be public.
I'd only consider this safe because you know that B contains everything in A (since it is derived from it).
If you only have a few properties, especially if they don't change often, just list them individually... it'll be easier to see exactly what your code is doing.
I can't for the life of me understand why you want to do this
You are passing an instance of Base class into the constructor of a derived class. What are you trying to do?
have you tried this = a instead of base = a?
The members are private, so you can't access them from even a derived class. Even if they were protected, you still couldn't access them on an instance of A from the B class.
In order to do this without reflection, the members will have to be public:
public class A
{
public int prop1 { get; set; }
public int prop2 { get; set; }
}
// Define other methods and classes here
public class B : A
{
public B(A a)
{
//base = a; doesn't work.
base.prop1 = a.prop1;
base.prop2 = a.prop2;
}
}
If you really want to do this and cannot access the properties via inheritance then you can do via reflection like this:
public class Aclass
{
public int Prop1 { get; set; }
public int Prop2 { get; set; }
}
public class Bclass : Aclass
{
public Bclass(Aclass aInstance)
{
CopyPropertiesFromAltInstance(aInstance);
}
public void CopyPropertiesFromAltInstance(Aclass aInstance)
{
PropertyInfo[] aProperties = aInstance.GetType().GetProperties();
PropertyInfo[] myProperties = this.GetType().GetProperties();
foreach (PropertyInfo aProperty in aProperties)
{
foreach (PropertyInfo myProperty in myProperties)
{
if (myProperty.Name == aProperty.Name && myProperty.PropertyType == aProperty.PropertyType)
{
myProperty.SetValue(this, aProperty.GetValue(aInstance));
}
}
}
}
}

Access base class(list) properties from derived class c#

I need to access base class properties which is a list from derieved class. Below is the example.I need this for unit testing.
class child : List<Parent>
{
//this class is empty.
}
class Parent
{
public List<Seller> Seller
{
get;
set;
}
public string Id
{
get;
set;
}
}
Am not able to access any properties of parent class . Please help.
unit test code
[Test]
public class test()
{
child a = new child();
a. // not showing any properties of parent
}
if you want to get a.ID , a.Seller you have to declare:
class child :Parent
{
//this class is empty.
}
If you derive from a List<T> you will inherit its abilities, not the abilities from T. What you can do is access one T in the list to access its properties.
public class Parent
{
public bool IAmAParent { get; set; }
}
public class Child : List<Parent>
{ }
var c = new Child();
c[0].IAmAParent = true;
From what I'm seeing I have the feeling you are confused about the inheritance you need. If you need to access the Parent's properties in the Child then it should inherit from the Parent, then put into a list, not the opposite.
public class Parent
{
public bool IAmAParent { get; set; }
}
public class Child : Parent
{ }
var c = new List<Child>();
c[0].IAmAParent = true;

Categories