derived entity instance in base type is null at initialization time - c#-4.0

I have say ClassA entity = new ClassA(){firstname="blah", age=28}
Also class A inherit a ClassB, so in ClassB contructor I want to do something like ClassB()
{ do something with classA entity, but the think is that the entity instance is still null, it goes thru the newing up stage then after the values firstname and age get set, is there a way around this to be able to get the not null instance of the derived class and pass it to the base class? Thankx. Using C# 4.

are you calling ClassA's constructor from ClassB?
public class ClassA
{
}
public class classB
{
public ClassB(): base()
{
//Do something with ClassA
}
}

in client code i have ClassA c = new ClassA(){firstname=""}
in the library it goes like this:
public partial class ClassA: ClassB
{
}
public class classB
{
public ClassB()
{
AddValidation(..);//here i want to acces the instance of entity ClassA that was populated in client code.
}
}

Related

Creating object of parent child class together in one line?

I wrote this but i can't understand what is this.
Public ClassA {
//some methods here
}
Public ClassB extends ClassA {
Public static void main(String[] args) {
ClassA abc=new ClassB
//What is purpose of this line and what advantage it gives us. I accidently wrote this but compiler (Eclipse not generating any error on this statement).
}
You happened to stumble across the distinction of static and dynamic type for a variable and its connection to the inheritance relation.
Your variable abc has a static type ClassA. Hence the compiler will only let you use methods defined in that class on that variable. After your initialization of abc, it has dynamic type ClassB.
Since ClassB extends ClassA, it has every method and attribute of ClassA (and maybe more) and it is OK to use is through abc.

Class to inherit the constructor of its base class

I would like to know if I can access the constructor of the base class in its derived classes in C#. If yes please let me know how could we make it. Thanks in advance.
You can call the base class constructor as part of the execution of the derived class constructor
public MyBase
{
public MyBase() { }
}
public Derived
{
public Derived() : base() { }
}
When using this pattern, you are said to be using the base class initializer.
For more background, see the base keyword and instance constructors on MSDN.

Make property in parent object visible to any of its contained objects

I have a class CalculationManager which is instantiated by a BackgroundWorker and as such has a CancellationRequested property.
This CalculationManager has an Execute() method which instantiates some different Calculation private classes with their own Execute() methods which by their turn might or might not instantiate some SubCalculation private classes, in sort of a "work breakdown structure" fashion where each subclass implements a part of a sequential calculation.
What I need to do is to make every of these classes to check, inside the loops of their Execute() methods (which are different from one another) if some "global" CancellationRequested has been set to true. I put "global" in quotes because this property would be in the scope of the topmost CalculationManager class.
So, question is:
How can I make a property in a class visible to every (possibly nested) of its children?
or put down another way:
How can I make a class check for a property in the "root object" of its parent hierarchy? (well, not quite, since CalculationManager will also have a parent, but you got the general idea.
I would like to use some sort of AttachedProperty, but these classes are domain objects inside a class library, having nothing to do with WPF or XAML and such.
Something like this ?
public interface IInjectable {
ICancelStatus Status { get; }
}
public interface ICancelStatus {
bool CancellationRequested { get; }
}
public class CalculationManager {
private IInjectable _injectable;
private SubCalculation _sub;
public CalculationManager(IInjectable injectable) {
_injectable = injectable;
_sub = new SubCalculation(injectable);
}
public void Execute() {}
}
public class SubCalculation {
private IInjectable _injectable;
public SubCalculation(IInjectable injectable) {
_injectable = injectable;
}
}
private class CancelStatus : ICancelStatus {
public bool CancellationRequested { get; set;}
}
var status = new CancelStatus();
var manager = new CalculationManager(status);
manager.Execute();
// once you set status.CancellationRequested it will be immediatly visible to all
// classes into which you've injected the IInjectable instance

initializing derived class member variables using base class reference object

I came across a lot of code in our company codebase with the following structure
class Base
{
public Base (var a, var b)
{
base_a = a;
base_b = b;
}
var base_a;
var base_b;
}
class Derived:Base
{
publc Derived (var a,b,c,d): base (a,d)
{
der_c = c;
der_d = d;
}
var der_c;
var der_d;
var der_e;
}
class Ref
{
Base _ref;
public Ref( var a,b,c,d)
{
_ref = new Derived (a,b,c,d)
}
public void method( )
{
_ref.der_e = 444; // won't compile
}
}
What is the correct way to initialize der_e ? What is the advantages of having a reference of base class and using an object derived class for _ref ? Just the fact that using a base class reference can hold multiple derived class objects ? If that's the case, should all the member variables of derived class be initialized during construction itself (like this: _ref = new Derived (a,b,c,d) ). What if I want to initialize _ref.der_e later in a method ? I know I can do this (var cast_ref = _ref as Derived; cast_ref.der_e = 444) but this look doesn't seem to the best practice. What is the idea of having such a structure and what is the correct of initializing a member of a derived class object after it has been constructed ?
Those are too many questions in a single post.
What is the correct way to initialize der_e ?
For initializing der_e you will have to have Reference of Derived class as it knows about the der_e property and not Base class.
What is the advantages of having a reference of base class and using
an object derived class for _ref ?
Yes that's called Polymorphism which is the essence of Object Oriented Programming. It allows us to hold various concrete implementations without knowing about the actual implementation.
If that's the case, should all the member variables of derived class
be initialized during construction itself (like this: _ref = new
Derived (a,b,c,d) )
There is no such rule. It depends on your scenario. If the values are not meant to be changed after the creation of the object and the values are known before hand during construction of the object then they should be initialized during construction.
Again if there are various scenarios like sometimes values are known and sometimes not then there can be Overloaded Constructors, which take different arguments.
What if I want to initialize _ref.der_e later in a method ?
That is perfectly fine, it depends on what you are trying to achieve. The question is not a concrete one but an abstract one in which it is difficult to comment on what you are trying to achieve.
I know I can do this (var cast_ref = _ref as Derived; cast_ref.der_e =
444) but this look doesn't seem to the best practice.
I am sharing some Java code which is similar to C# as I am from Java background
//This class knows about Base and nothing about the Derived class
class UserOfBase{
Base ref;
//Constructor of UserOfBase gets passed an instance of Base
public UserOfBase(Base bInstance){
this.ref = bInstance;
}
//Now this class should not cast it into Derived class as that would not be a polymorphic behavior. In that case you have got your design wrong.
public void someMethod(){
Derived derivedRef = (Derived)ref; //This should not happen here
}
}
I am sharing some references which would help you with this, as I think the answer can be very long to explain.
Factory Pattern
Dependency Injection
Head First Design Patterns
Posts on SO regarding polymorphism
You can create a constructor in your derived class and map the objects or create an extension method like this:
public static class Extensions
{
public static void FillPropertiesFromBaseClass<T1, T2>(this T2 drivedClass, T1 baseClass) where T2 : T1
{
//Get the list of properties available in base class
System.Reflection.PropertyInfo[] properties = typeof(T1).GetProperties();
properties.ToList().ForEach(property =>
{
//Check whether that property is present in derived class
System.Reflection.PropertyInfo isPresent = drivedClass.GetType().GetProperty(property.Name);
if (isPresent != null && property.CanWrite)
{
//If present get the value and map it
object value = baseClass.GetType().GetProperty(property.Name).GetValue(baseClass, null);
drivedClass.GetType().GetProperty(property.Name).SetValue(drivedClass, value, null);
}
});
}
}
for example when you have to class like this:
public class Fruit {
public float Sugar { get; set; }
public int Size { get; set; }
}
public class Apple : Fruit {
public int NumberOfWorms { get; set; }
}
you can initialize derived class by this code:
//constructor
public Apple(Fruit fruit)
{
this.FillPropertiesFromBaseClass(fruit);
}

Does not contain a constructor that takes 0 arguments

I get an error stating "Products does not contain a constructor that takes 0 arguments" from the following code:
public class Products
{
string id;
string name;
double price;
int soldCount;
int stockCount;
public Products(string id, string name, double price,
int soldCount, int stockCount, double tax)
{
this.id = id;
this.name = name;
this.price = price;
this.soldCount = soldCount;
this.stockCount = stockCount;
}
}
//I have got some get and set values for the code above
//but it would have been too long to put in here
public class FoodProducts : Products
{
public FoodProduct()
{
Console.WriteLine("This is food product");
}
public void Limit()
{
Console.WriteLine("This is an Attribute of a Product");
}
}
Several rules about C# come into play here:
Each class must have a constructor (In order to be, well constructed)
If you do not provide a constructor, a constructor will be provided for you, free of change, automatically by the compiler.
This means that the class
class Demo{}
upon compilation is provided with an empty constructor, becoming
class Demo{
public Demo(){}
}
and I can do
Demo instance = new Demo();
If you do provide a constructor (any constructor with any signature), the empty constructor will not be generated
class Demo{
public Demo(int parameter){}
}
Demo instance = new Demo(); //this code now fails
Demo instance = new Demo(3); //this code now succeeds
This can seem a bit counter-intuitive, because adding code seems to break existing unrelated code, but it's a design decision of the C# team, and we have to live with it.
When you call a constructor of a derived class, if you do not specify a base class constructor to be called, the compiler calls the empty base class constructor, so
class Derived:Base {
public Derived(){}
}
becomes
class Derived:Base {
public Derived() : base() {}
}
So, in order to construct your derived class, you must have a parameterless constructor on the base class. Seeing how you added a constructor to the Products, and the compiler did not generate the default constructor, you need to explicitly add it in your code, like:
public Products()
{
}
or explicitly call it from the derived constructor
public FoodProduct()
: base(string.Empty, string.Empty, 0, 0, 0, 0)
{
}
Since Products has no constructor that takes 0 arguments, you must create a constructor for FoodProducts that calls the constructor of Products will all the required arguments.
In C#, this is done like the following:
public class FoodProducts : Products
{
public FoodProducts(string id, string name, double price, int soldCount, int stockCount, double tax)
: base(id, name, price, soldCount, stockCount, tax)
{
}
public void Limit()
{
Console.WriteLine("This is an Attribute of a Product");
}
}
If you don't want to add this constructor to FoodProducts, you can also create a constructor with no parameter to Products.
the constructor of the inherited class needs to construct the base class first. since the base class does not have a default constructor (taking 0 arguments) and you are not using the non-default constructor you have now, this won't work. so either A) add a default constructor to your base class, in which case the code of the descending class needs no change; or B) call the non-default constructor of the base class from the constructor of the descending class, in which case the base class needs no change.
A
public class Products
{
public Products() { }
}
public class FoodProducts : Products
{
public FoodProducts() { }
}
B
public class Products
{
public class Products(args) { }
}
public class FoodProducts : Products
{
public FoodProducts(args) : base(args) { }
}
some of this is explained rather OK on msdn here.
As you inherit from Products, you must call a base construct of Products in your own class.
You didn't write:base(id, name, ....) so C# assumes you call the default parameterless constructor, but it doesn't exist.
Create a default parameterless constructor for Products.
Just add
public Products()
{
}
in your products class And you will not get error
Reason:
There exists a default constructor with 0 parameter for every class. So no need to define/write it explicitly (by programmer) BUT when you overload a default constructor with your desired number and type of parameters then it becomes a compulsion to define the default constructor yourself (explicitly) along with your overloaded constructor

Resources