C# Factory Pattern - Base method will always get called - c#

I'm wondering why in the following example does the base method always get called even though I'm overriding it when the Factory Pattern "Builder" returns a new instance of the object?
interface FactoryInter
{
void MakeDetails();
}
class Builder {
public static Builder getObject(string obj)
{
if(obj == "Cont")
{
return new Cont();
}else{
return new Builder();
}
}
public void MakeDetails()
{
Console.WriteLine("I will always get called..");
}
}
class Cont : Builder, FactoryInter {
public void MakeDetails()
{
Console.WriteLine("Hello..");
}
}
public class Test
{
public static void Main()
{
Builder b = new Builder();
b = Builder.getObject("Cont");
b.MakeDetails();
// your code goes here
}
}
Any help would be greatly appreciated

You do not override it. You are hiding it. Method Cont.MakeDetails() is hiding the base class's MakeDetails method. For more details please see the below example:
class Base
{
public void Hidden()
{
Console.WriteLine("Base!");
}
public virtual void Overrideable()
{
Console.WriteLine("Overridable BASE.");
}
}
class Derived : Base
{
public void Hidden()
{
Console.WriteLine("Derived");
}
public override void Overrideable()
{
Console.WriteLine("Overrideable DERIVED");
}
}
Now testing them yields these results:
var bas = new Base();
var der = new Derived();
bas.Hidden(); //This outputs Base!
der.Hidden(); //This outputs Derived
((Base)der).Hidden();
//The above outputs Base! because you are essentially referencing the hidden method!
//Both the below output Overrideable DERIVED
der.Overrideable();
((Base)der).Overrideable();
To override it, mark the base method as virtual and the derived one as override.

Related

Why is my interface method call ignored in a C# generic?

I am quite new to C# and I cannot understand the behaviour of a class in my project.
I am using an interface that defines a generic with a type constraint which is another interface.
When I call the generic, I know that a certain method exists on the argument (because of the type constraint), but this method doesn't get executed when I call it.
The only workaround I have so far is to include the method call into the type-specific method overloads.
This may be better explained with the following snippet with an equivalent type structure:
public interface ITrickable
{
void GetRabbitOut();
}
public interface IMagic
{
void DoTricks<T>(T obj) where T : ITrickable;
}
public class Hat : ITrickable
{
public void LiftUp() { Console.WriteLine("Lifting up the hat..."); }
public void GetRabbitOut() { Console.WriteLine("A rabbit came out the hat !"); }
}
public class Box : ITrickable
{
public void OpenDoubleBottom() { Console.WriteLine("Opening the box..."); }
public void GetRabbitOut() { Console.WriteLine("A rabbit came out the box !"); }
}
public abstract class Magician : IMagic
{
public abstract void DoTricks<T>(T obj) where T : ITrickable;
}
Now if I call DoTricks(new Hat()); DoTricks(new Box()); with the class below:
public class Houdini : Magician
{
public override void DoTricks<T>(T obj)
{
try {
DoTricks(obj); }
catch {
throw new NotImplementedException(); }
}
public void DoTricks(Hat obj)
{
obj.LiftUp();
obj.GetRabbitOut();
}
public void DoTricks(Box obj)
{
obj.OpenDoubleBottom();
obj.GetRabbitOut();
}
}
The output is as expected:
Lifting up the hat...
A rabbit came out the hat !
Opening the box...
A rabbit came out the box !
But if the class is defined as this one below:
public class Genesta : Magician
{
public override void DoTricks<T>(T obj)
{
try {
DoTricks(obj);
obj.GetRabbitOut(); } // <--- This seems to be ignored !?
catch {
throw new NotImplementedException(); }
}
public void DoTricks(Hat obj)
{
obj.LiftUp();
}
public void DoTricks(Box obj)
{
obj.OpenDoubleBottom();
}
}
The output is
Lifting up the hat...
Opening the box...
The question is why does GetRabbitOut is not called in the second class?
EDIT: The calling code is:
public static void Main(string[] args)
{
var houdini = new Houdini();
var hat = new Hat();
var box = new Box();
houdini.DoTricks(hat);
houdini.DoTricks(box);
Console.ReadLine();
}
Notice your method calls (I imagine it looked something resembling this):
Genesta g = new Genesta();
g.DoTricks(new Hat());
g.DoTricks(new Box());
Since you call g.DoTricks(new Hat()) rather than g.DoTricks<Hat>(new Hat()), no surprises that the exact method of the Genesta class that is invoked is DoTricks(T obj) and not DoTricks<T>(T obj). And when considering the implementation of DoTricks(T obj)...
public void DoTricks(Hat obj)
{
obj.LiftUp();
}
public void DoTricks(Box obj)
{
obj.OpenDoubleBottom();
}
The result is actually what you can expect from these methods!
If, however, you would call the generic method like this...
g.DoTricks<Hat>(new Hat());
You would fall into an infinite recursion, as the method would call itself indefinitely. DoTricks<T>(T obj) will always call itself and not one of the specialized overloads DoTricks(Hat) or DoTricks(Box), since the compiler cannot know before runtime that T will in fact be either Hat or Box.
By the way, the Houdini class experiences the same effect - it just so happens that its specific DoTricks(Hat) and DoTricks(Box) methods produce the result that you expected from calling DoTricks<T>(T obj).

How do I use an overridden property value in a higher class?

I'm using IoC to define some behavior in my inherited class. I have a property
protected virtual bool UsesThing { get { return true; } }
in my top-level class.
In my inherited class I have
protected override bool UsesThing { get { return false; } }
I'm using the property in my top level class, and it's using the top-level value. Is there a way to make it use the inherited value? I thought that's what virtual was supposed to do.
Code Example:
using System;
public class Program
{
public static void Main()
{
B b = new B();
b.PrintThing();
//I want this to print the value for B
}
public class A
{
protected virtual bool Enabled
{
get
{
return true;
}
}
public void PrintThing()
{
Console.WriteLine(this.Enabled.ToString());
}
}
public class B : A
{
protected override bool Enabled
{
get
{
return false;
}
}
}
}
Here's a Dot Net Fiddle demonstrating my problem
You could do something like this:
https://dotnetfiddle.net/SOiLni
A in of itself knows nothing of B's implementation, so you have to instantiate an object of B in order to access its overriden property.
Slightly modified version of your fiddle:
public class Program
{
public static void Main()
{
A a = new A();
a.PrintThing();
A newA = new B();
newA.PrintThing();
}
public class A
{
protected virtual bool Enabled
{
get
{
return true;
}
}
public void PrintThing()
{
Console.WriteLine(this.Enabled.ToString());
}
}
public class B : A
{
protected override bool Enabled
{
get
{
return false;
}
}
}
}
Given your code example, A's Enabled will be printed, as it should.
When you create an A it knows nothing about B, so polymorphically, you can't expect it to use its value. This makes since, because if you had a class C that also derived from A, it wouldn't know what to use!
On the other hand, if you had written:
public static void Main()
{
A a = new B();
a.PrintThing();
}
You would expect (correctly) that it would use B's override, as you created an instance of that type.
You must have some other issue with your code. This code will print 'true' and 'false' respectively:
public class BaseClass {
public virtual bool DoesSomething {
get {
return true;
}
}
public void Print() {
Console.WriteLine(DoesSomething);
}
}
public class ChildClass : BaseClass {
public override bool DoesSomething {
get {
return false;
}
}
}
Then using these classes:
BaseClass bc = new BaseClass();
bc.Print();
ChildClass sc = new ChildClass();
sc.Print();
If I was to guess you are probably creating instances of the parent class even though your intention is to create instances of the child class.

Get current class at runtime in a static method?

How can I get the type (not a name string, but a type itself) of the current class, in a static method of an abstract class?
using System.Reflection; // I'll need it, right?
public abstract class AbstractClass {
private static void Method() {
// I want to get CurrentClass type here
}
}
public class CurrentClass : AbstractClass {
public void DoStuff() {
Method(); // Here I'm calling it
}
}
This question is very similar to this one:
How to get the current class name at runtime?
However, I want to get this information from inside the static method.
public abstract class AbstractClass
{
protected static void Method<T>() where T : AbstractClass
{
Type t = typeof (T);
}
}
public class CurrentClass : AbstractClass
{
public void DoStuff()
{
Method<CurrentClass>(); // Here I'm calling it
}
}
You can gain access to the derived type from the static method simply by passing the type as a generic type argument to the base class.
I think you will have to either pass it in like the other suggestion or create a stack frame, I believe if you put an entire stack trace together though it can be expensive.
See http://msdn.microsoft.com/en-us/library/system.diagnostics.stacktrace.aspx
if you are calling this static method only from derived classes you can use 'System.Diagnostics.StackTrace' like
abstract class A
{
public abstract string F();
protected static string S()
{
var st = new StackTrace();
// this is what you are asking for
var callingType = st.GetFrame(1).GetMethod().DeclaringType;
return callingType.Name;
}
}
class B : A
{
public override string F()
{
return S(); // returns "B"
}
}
class C : A
{
public override string F()
{
return S(); // returns "C"
}
}
The method can't be static if you're going to call it without passing in a type. You can do this:
public abstract class AbstractClass {
protected void Method() {
var t = GetType(); // it's CurrentClass
}
}
If you also need it to be accessible from a static context, you can add an overload, even a generic overload, e.g.:
public abstract class AbstractClass {
protected static void Method<T>() {
Method(typeof(T));
}
protected static void Method(Type t) {
// put your logic here
}
protected void Method() {
Method(GetType());
}
}

How do i change the call order of nested constructors (child before abstract parent)

The code below throws an exception because the abstract constructor is called before the child constructor.
I need to provide an abstract class to capsule some logic from a different part of the program. However i also need to check if the abstract members are initialised correctly rigth after creation without the childclass having any influence over this.
the compiling example below should illustrate my question.
using System;
namespace Stackoverflow
{
class Program
{
static void Main(string[] args)
{
var x = new Thing(5);
var y = new Child(x);
}
}
class Child : AbstractParent
{
Thing childthing;
public Child(Thing provided) : base(){
childthing = provided;
}
public override void Initialise(){
//Exception is thrown here - childthing is still null
parentthing = childthing.Add(1);
}
}
abstract class AbstractParent
{
protected Thing parentthing;
public AbstractParent(){
Initialise();
AssertThingyNotNull();
}
private void AssertThingyNotNull(){
if (parentthing == null) throw new Exception("Waaa");
}
public abstract void Initialise();
}
class Thing
{
private int i;
public Thing(int i){
this.i = i;
}
public Thing Add(int b){
i += b;
return new Thing(i);
}
}
}
Edit #1:
Is there some way to do this by reflecting into the caller (should be the creator of child rigth?) and then reacting on the end of that call?
Edit #2:
Getting the .ctor that creates the child is easy. Manipulating the methods seems something between impossible and a bad idea.
foreach (StackFrame frame in new StackTrace().GetFrames())
{
Console.WriteLine(frame.GetMethod().Name);
}
You can't, basically. This is why you should avoid calling virtual (or abstract) members from a constructor as far as possible - you could end up with code which is running with an incomplete context. Any variable initializers are executed before the base class constructor is called, but none of the code within the constructor body is.
If you need to perform initialization and only want to do that when the derived class constructor is running, then just call Initialise from the derived class constructor to start with.
You can do something similar to what Microsoft did with InitializeComponent()
then let the children call it whenever it can.
Try this.
Edited = cleaner version.
using System;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
var x = new Thing(5);
var y = new Child(x);
}
}
class Child : AbstractParent
{
public Child(Thing provided)
: base()
{
parentthing = provided;
base.Initialise();
}
}
abstract class AbstractParent
{
protected Thing parentthing;
public AbstractParent()
{
}
private void AssertThingyNotNull()
{
if (parentthing == null) throw new Exception("Waaa");
}
public void Initialise()
{
AssertThingyNotNull();
}
}
class Thing
{
private int i;
public Thing(int i)
{
this.i = i;
}
public Thing Add(int b)
{
i += b;
return new Thing(i);
}
}
}

"Base class params are not always used" code smell

Suppose you had such code:
public Base
{
abstract void Register();
}
public Registrator1: Base
{
override void Register()
{
//uses the current state of the object to populate the UI captions
}
}
public Registrator2: Base
{
override void Register()
{
//uses the current state of the object to populate the UI captions
}
}
But When you receive a new business rule asking you to write Registrator3 which actually registers based on some parameter and you change your code base to the next:
public Base
{
abstract void Register(externalParam);
}
public Registrator1: Base
{
override void Register(externalParam)
{
//uses the current state of the object to populate theUI
}
}
public Registrator2: Base
{
override void Register(externalParam)
{
//uses the current state of the object to populate the UI
}
}
public Registrator3: Base
{
override void Register(externalParam)
{
//uses a DDD - service passed in the params to populate the UI
}
}
But Registrator1 and Registrator2 do not need that param and the code becomes smelly. What are the ways to re-write this code?
You could use an object as a parameter here; which is commonly used in scenarios where the number of parameters can vary depending on the call being used.
struct RegistrationInfo
{
public static readonly RegistrationInfo Empty = new RegistrationInfo();
public string Username;
public string CustomerName;
public string Validity;
}
abstract class Base
{
public abstract void Register(RegistrationInfo info);
// If you want to retain the paramaterless call:
public void Register()
{
Register(RegistrationInfo.Empty);
}
}
class Registrar1 : Base
{
public override void Register(RegistrationInfo info)
{
if (info.Username == null) throw new ArgumentNullException("info.Username");
}
}
class Registrar2 : Base
{
public override void Register(RegistrationInfo info)
{
if (info.CustomerName == null) throw new ArgumentNullException("info.CustomerName");
}
}
This has the advantage that you don't need to change method parameters (which is breaking interface) each time a parameter is added. The usage also becomes somewhat self-documenting:
var r = new Registrar1();
r.Register(new RegistrationInfo(){ Username = "JimJoe" });
r.Register(RegistrationInfo.Empty);
It's like air freshener for this type of code smell, while it's still smelly; you can make it smell nicer.
Finally you can make the call-site cleaner by making it a params argument (this has a small amount of overhead); in all honesty though it is more smelly because it's a language hack. Finally you could improve it with generics:
class RegistrationInfo
{
}
class RegistrationInfo1 : RegistrationInfo
{
public string Arg;
}
class RegistrationInfo2 : RegistrationInfo
{
public int Arg;
}
interface IBase<in TRegistration>
where TRegistration : RegistrationInfo
{
void Register(TRegistration registration);
}
class Base : IBase<RegistrationInfo>
{
public void Register(RegistrationInfo registration)
{
}
}
class Registrar1 : IBase<RegistrationInfo1>
{
public void Register(RegistrationInfo1 arg)
{
}
}
class Registrar2 : IBase<RegistrationInfo2>
{
public void Register(RegistrationInfo2 arg)
{
}
}
Is it not possible to contain the logic for externalParam in Registrator3?
In other words, Registrator3 uses the param, then calls the unmodified parameterless base?
A lot really depends on where the logic belongs. If it is something intrinsic to the base, then put it in the base, and either overload the Register() function or supply a default value for the param so that sub classes don't need to provide it.
Assuming you want to reuse the registration logic from the base class, you could update the code as follows:
public class Base
{
public virtual void Register(object externalParam)
{
// base registration logic goes here
}
}
public class Registrator1: Base
{
public override void Register(object externalParam)
{
base.Register(null);
// custom registration logic goes here
}
}
public class Registrator2: Base
{
public override void Register(object externalParam)
{
base.Register(null);
// custom registration logic goes here
}
}
public class Registrator3: Base
{
public override void Register(object externalParam)
{
base.Register(externalParam);
// custom registration logic goes here
}
}
HTH,
Cosmin
EDIT: Updated code to compile.

Categories

Resources