Use inheritance and modify the parameters in some functions - c#

I need to create math problems. Arithmetic, Comparison 2 numbers.. every class contains similiar features like CheckTheAnswer and GenerateProblem, but each one of them receives different parameters. Here is an example what I'm trying to do.
public class Problem<T>
{
public virtual bool CheckTheAnswer()
{
return false;
}
public static T GenerateProblem()
{
return T;
}
}
public class Arithmetic : Problem<Arithmetic>
{
public bool CheckTheAnswer(decimal result)
{
...
}
public static Arithmetic GenerateProblem(Tuple<int, decimal, decimal> condition)
{
...
}
}
public class Comparison2Numbers : Problem<Comparison2Numbers>
{
public bool CheckTheAnswer(decimal result1, decimal result2)
{
...
}
public static Comparison2Numbers GenerateProblem(Tuple<decimal, decimal> condition)
{
...
}
}
I was thinking in interfaces, but I realized in interfaces can't have static functions.
Thanks in advance.
OK, the question is.. is there a way to do this?
Arithmetic a = new Arithmetic();
Problem<Arithmetic> p = a;
And get the functions from Arithmetic class. Maybe this is not the best way to generalize this problems, what do you opine?

I think this is the kind of problem where you probably want an abstract factory for your generators, rather than static methods. You can use the constructors of individual factories to pass in data with varying arguments. Each will have a fixed Create method though.
interface IProblemFactory<T> where T : IProblem<T>
{
T Create();
}
class ArithmeticProblemFactory : IProblemFactory<Arithmetic>
{
private Tuple<int, decimal, decimal> condition;
public ArithmeticProblemFactory(Tuple<int, decimal, decimal> condition) {
this.condition = conditionl
}
Arithmetic IProblemFactory<Arithmetic>.Create() {
...
}
}

To get the behavior of polymorphic creation, the abstract factor pattern would be best for this. See Mark's answer for an example of how to set this up.
But you also need the ability to check the answer with different number of arguments. From your examples, it seem that you will always expect a type of decimal for each of the arguments. Assuming this is correct, you can make CheckTheAnswer a variadic method. I might also suggest adding a polymorphic property to access the desired number of arguments. So we now have:
public abstract class Problem<T>
{
public abstract int ResultCount { get; }
public abstract bool CheckTheAnswer(params decimal[] results);
}
And the a base class could be along the lines of:
public class Arithmetic : Problem<Arithmetic>
{
public override int ResultCount
{
get
{
return 2;
}
}
public override bool CheckTheAnswer(params decimal[] results)
{
if(results.Length != ResultCount)
throw new ArgumentException("Only expected " + ResultCount + " arguments.");
...
}
}
While this doesn't provide compile-time type safety in the number of arguments, it will allow you to solve your problem using run-time guarantees.

Related

is it posible to relate two different classes that contains same method but with different parameters?

I'm defining an Interface to group two different subclasses. Each class implements the inherit method but each needs different parameters to be able to work.
Here's the interface.
public interface Billable()
{
decimal Bill();
}
Here's the first class
public class HourlyEmployee : Billable
{
public decimal Bill(int hoursWorked, decimal pricePerHour) { }
}
Here's the second
public class CommissionEmployee : Billable
{
public decimal Bill(decimal commisionPercentage) { }
}
As you can see, conceptually they use the method to achieve the same, which is charging for a service. That's why I initially thought about inheritance, but it seems that's not the best approach.
What other alternatives can make the classes relate to each other?
This doesn't directly answer the question in your title, but you did ask for other alternatives...
Your interface is a contract, guaranteeing that your classes will have a Bill() function that returns a decimal. But that doesn't mean you have to accept the parameters in that method.
Here the constructors for each class accept the parameters. The Bill() method does the calculation to return the appropriate value.
public interface IBillable
{
decimal Bill();
}
public class HourlyEmployee : IBillable
{
private int hoursWorked;
private decimal pricePerHour;
public HourlyEmployee(int hoursWorked, decimal pricePerHour)
{
this.hoursWorked = hoursWorked;
this.pricePerHour = pricePerHour;
}
public decimal Bill()
{
return hoursWorked * pricePerHour;
}
}
public class CommissionEmployee : IBillable
{
private int commissionPercentage;
public CommissionEmployee(int commissionPercentage)
{
this.commissionPercentage = commissionPercentage;
}
public decimal Bill()
{
// do some calculation using commissionPercentage and return a value...
}
}
Not sure if this is the best approach, but I think your approach of using an interface is good (which I'd call IBillable by convention).
But you should not try to accommodate all the required values for the calculation as parameters in the interface method, as this limits your extensibility, what if you come across a new kind of employee who needs one more value for bill calculation. Interface is a contract which should not change, hopefully ever. Method suggested below doesn't have that problem.
One suggestion is to use another class (let's say BillCalculator) and move the different parameters required by the Billable interface to properties of that class.
public abstract class BillCalculator: IBillable
{
abstract decimal Bill();
}
public class HourlyBillCalculator: BillCalculator
{
public int HoursWorked { get; set; }
public decimal PricePerHour { get; set; }
public HourlyBillCalculator(int hoursWorked, decimal pricePerHour)
{
HoursWorked = hoursWorked;
PricePerHour = pricePerHour;
}
public override Bill()
{
// Calculate the Bill
}
}
public class CommisionBillCalculator: BillCalculator {
public decimal CommisionRate { get; set; }
public CommisionBillCalculator(decimal rate)
{
CommisionRate = rate;
}
public override Bill() {
// Calculate the Bill
}
}
Corresponding Calculator class has to be instantiated using a factory pattern or something to fit the need. Then it's just a matter of calling the Bill method, which will use the instance properties to calculate the value.
That will let you keep interface signature consistent.
Note: Syntax may be off, but hope you get the idea.
Obviously what you propose produces a syntax error as every implementation of the interface should implement all its prototyped methods. By definition, implementing a prototype means having the same parameters, that's why you cannot have multiple parameters for the same method. However, you can take the advantage of the optional parameters introduced in .NET 4.0
So you can have something like this.

C# Pass a Class as a parameter

I have an Interface, that has some methods
interface IFunction
{
public double y(double x);
public double yDerivative(double x);
}
and I've got static classes, that are implementing it.
static class TemplateFunction:IFunction
{
public static double y(double x)
{
return 0;
}
public static double yDerivative(double x)
{
return 0;
}
}
I want to pass this classes as a parameter to another function.
AnotherClass.callSomeFunction(TemplateFunction);
And some other class that catches the request
class AnotherClass
{
IFunction function;
public void callSomeFunction(IFunction function)
{
this.fuction = function;
}
}
Well, it doesn't work... I've tried to use the Type expression, but that seams to break the idea of using an interface. Does anyone have an idea, how to correct the code?
Static classes can't implement interfaces, but you can easily overcome this by making your class non static and a generic method:
class AnotherClass
{
IFunction function;
public void callSomeFunction<T>()
where T: IFunction, new()
{
this.fuction = new T();
}
}
This is much close to the syntax you wanted:
AnotherClass.callSomeFunction<TemplateFunction>();
But I actually think that this way is too complicated and likely to confuse someone, you should follow Servy's approach which is way simpler:
AnotherClass.callSomeFunction(TemplateFunction.Instance);
The conceptual way of getting a static class to implement an interface is to use a singleton, even if that singleton contains no state:
public sealed class TemplateFunction : IFunction
{
private TemplateFunction() { }
private static TemplateFunction instance = new TemplateFunction();
public static TemplateFunction Instance { get { return instance; } }
public double y(double x)
{
return 0;
}
public double yDerivative(double x)
{
return 0;
}
}
Another option is to just not use an interface, and instead have your method accept one or more delegates. It's fine if you only need a single method, if you have two it can sometimes be okay, and sometimes not. If you have more than two, it's usually a problem.
public class AnotherClass
{
public static void callSomeFunction(Func<double, double> y
, Func<double, double> yDerivitive)
{
//store delegates for later use
}
}
AnotherClass.callSomeFunction(TemplateFunction.y, TemplateFunction.yDerivative);
How about you use a generic method to catch the type that you are calling for.
Like this:
public void callSomeFunction<T>()
{
//the type is T
//you can create an instance of T with System.Activator.CreateInstance(T) and T's methods
//alternatively if the classes are static you can call the methods with reflection knowing only their name.
}
And anyway, if the reason you want to do this is because you want to have multiple classes that implement the same methods and you want to write a method that will call a certain implementation of those methods based on type, then other solutions might be in order, like overloading.
Or if indeed this is what you want to do, then keep in mind that passing an interface won't allow you to use the approach i presented you with, because the Activator needs to have access to the Type so that it can create an instance.
You can do as Allon said and change the TemplateFunction to none static and then do this:
var anotherClass = new AnotherClass();
var templateFunction = new TemplateFunction();
anotherClass.callSomeFunction(templateFunction);

Overloaded Method..why is base class given precedence?

In the following code, i have an overloaded method, one that takes a parameter of type ClazzA and the other of type ClazzB. In the code shown, the first GetDescription method (the one that takes ClazzA as a parameter) is called. I think i understand why.
My question is..is there an elegant way of having the method that takes clazzB called first if the underlying object is of type classB (without having to inspect each object and casting it to clazzB)?
public class ClazzA
{
public virtual string Descr { get { return "A"; } }
}
public class ClazzB : ClazzA
{
public override string Descr { get { return "B"; } }
}
public static class test
{
public static void Main()
{
ClazzA test = new ClazzB();
GetDecription(test);
}
public static void GetDecription(ClazzA someClazz)
{
Debug.WriteLine("I am here");
}
public static void GetDecription(ClazzB someClazz)
{
Debug.WriteLine("I want to be here");
}
}
Output: "I am here"
I really want the 2nd method to be called since 'test' is of type ClassB. Curerently the only two solutions i have is:
if (test is ClazzB)
return GetDescription( (ClazzB) test );
or
In ClassA do pretty much the same thing...check the type and delegate to the 2nd method
Both of these require inspection of the object to determine its type
Overloads are determined at compile time. The compile time type of the reference is ClazzA so that overload is chosen. What you are asking for is related to multiple dispatch. C# and many other languages like C++ and Java only support single dispatch (via virtual methods). There are a number of ways people have come up with to work around this. The purest OO way of doing this is the visitor pattern. You modify the classes to contain a method (Accept) which then passes the this reference to a method on the visitor (Visit). This works because you override the Accept method in each subclass so that this will be the object's actual type. All the visitor needs is a specific method for each subclass that you want to support (see wikipedia for more details).
A sample:
public class ClazzA
{
public virtual string Accept(ClassVisitor visitor)
{
return visitor.Visit(this);
}
}
public class ClazzB : ClazzA
{
public override string Accept(ClassVisitor visitor)
{
return visitor.Visit(this);
}
}
public abstract class ClassVisitor
{
public abstract string Visit(ClazzA a);
public abstract string Visit(ClazzB b);
}
public class GetDescriptionVisitor : ClassVisitor
{
public override string Visit(ClazzA a)
{
return "A";
}
public override string Visit(ClazzB b)
{
return "B";
}
}
Usage:
ClassVisitor visitor = new GetDescriptionVisitor();
ClazzA b = new ClazzB();
Console.WriteLine(b.Accept(visitor)); // prints "B"
Because the method overload resolution occurs at compile-time. In terms of dealing with this situation, if you are using C# 4 then you could use dynamic so that the overload resolution is deferred to execution-time.
dynamic instance = new ClazzB();
Console.WriteLine(GetDescription(instance));
Alternatively, you could use a Visitor Pattern something like the following but this double-dispatch approach feels like a lot of work. Note the repetitive Visit method that must be re-implement in every derived type!
public interface IVisitable
{
string Visit(DescriptionVisitor visitor);
}
public class ClazzA : IVisitable
{
public virtual string Visit(DescriptionVisitor visitor)
{
return visitor.Visit(this);
}
}
public class ClazzB : ClazzA
{
public override string Visit(DescriptionVisitor visitor)
{
return visitor.Visit(this);
}
}
public class DescriptionVisitor
{
public string Visit(ClazzA item) { return "Description A"; }
public string Visit(ClazzB item) { return "Description B"; }
}
Then the following will ultimately still call the overload in DescriptionVisitor that takes ClazzB.
var visitor = new DescriptionVisitor();
ClazzA a = new ClazzB();
Console.WriteLine(a.Visit(visitor));
What you're trying to do is probably better performed using polymorphism, like so:
public interface IProvideDescription {
string GetDescription();
}
public class A : IProvideDescription {
public string GetDescription() {
return "I'm an A";
}
}
public class B : IProvideDescription {
public string GetDescription() {
return "I'm a B";
}
}
// to execute:
IProvideDescription x = new A();
Console.WriteLine(x.GetDescription());
x = new B();
Console.WriteLine(x.GetDescription());
To answer the question in your title ("...why is the base class given precedence?"), look at what your variable test is declared as (answer: your base class). When the overload is selected, all the method call knows is that you're passing a variable of type ClazzA into it. Sure, you've assigned it an object of type ClazzB, but suppose your assignment statement was more complex:
ClazzA test = GiveMeSomeObject();
The method selection has to occur at compile time to provide type safety.
You can get the behaviour you want by using the "dynamic" keyword which was introduced in .Net 4.0. It evaluates the type at runtime and will pick the right overload.
public static class test
{
public static void Main()
{
dynamic test = new ClazzB();
GetDecription(test);
}
public static void GetDecription(ClazzA someClazz)
{
Debug.WriteLine("I am here");
}
public static void GetDecription(ClazzB someClazz)
{
Debug.WriteLine("I want to be here");
}
}
Generally it's not a responsibility of external class to identify class type.
if you need a polymorphic behavior, just put GetDescription into ClassA as virtual function and then override in ClassB - that will be conceptually correct.
As #roken mentioned, your example will actually result in B since the Descr property is overridden. If this is all you're doing, remove the ClazzB overload and use the polymorphic behavior you've already got. If you actually need to do something different in the methods and overloading is the best way to do that, you could do it via dynamic overload resolution:
GetDecription((dynamic)test);
However, this has some drawbacks, such as performance and a lack of compile-time testing that GetDescription(test) makes sense. I'd recommend doing a runtime check within GetDecription(ClazzA):
if (someClazz is ClazzB)
{
GetDescription((ClazzB)someClazz);
return;
}
You can get by with just a single GetDescription() method:
public String GetDescription(ClassA in) {
if (in is ClassB) {
return (in as ClassB).Descr
}
return in.Descr;
}

static abstract class

I need a way to create a static class where some constants can be case specific, but hard-coded.
What I really want to do is have a class where several constants are provided when the class is extended - I want the 'constants' hard-coded. I figured I will make the some abstract properties and define the get { return constant; } when extending the class.
I know that is not possible, so now I am facing two options and am wondering what would be best and why (if there are options I'm missing please let me know!)
Create a static class with nullable fields and throw an exception if the fields are null when the static method is called.
Give up the static class. Have a non-static class with abstract properties and create an instance of the object wherever I need it even though all the functionality really is static.
I know this might be subjective and case-dependant, however I am going around in circles when thinking about this and could really do with some external input. That plus I hope there might be away of doing what I want and I'm just thinking about this wrong.
Update: Code: I will try to write some code that describes what I'd like to accomplish. I know this code can't work!
Imagine that the abstract class Calculation is in a dll, used by many projects. The functionality is the same for all of them, just the Constant varies from project to project.
public abstract static class Calculation
{
private abstract int Constant { get; } //The constant is unknown at this time
public static int Calculate(int inputValue)
{
return inputValue * Constant;
}
}
The class Calc is defined in a separate project where the functionality is needed and the Constant is known.
public static class Calc : Calculation
{
private override int Constant { get { return 2; }
}
...
static class Program
{
[STAThread]
static void Main()
{
//At some point:
int result = Calc.Calculate(6);
}
}
I suppose the simplest way would be to create a non-static class and create an instance, however I fear having several instances of the class could be expensive and would like to prevent that if possible.
I can't see how I could write this as a singleton pattern without writing it again in each project - having only the Nested class in the dll. That doesn't prevent the implementor to just create an ordinary class and is likely to restart the debate for every project where the code is used.
Update #2 : What I ment with option one is this:
Class in a dll:
public static class Calculation
{
public int? Constant {get; set;}
public static int Calculate(int inputValue)
{
if (Constant == null)
throw new ArgumentNullException();
return inputValue * (int)Constant;
}
}
Usage of the function in a seperate project:
static class Program
{
[STAThread]
static void Main()
{
//At some point:
Calculation.Constant = 2;
int result = Calc.Calculate(6);
}
}
Option one is very simple and elegant, what bothers me about it that nothing forces the implementor to set the Constant. I fear an (admittedly unlikely) scenario where an obscure corner case will cause the property to not be set and for the code to fail (and Constant beeing the last suspect)...
You could make non-static classes that follow singleton, ensuring only one instance of the object ever to exist. I guess that could be the next best thing.
You can't want static and inheritance at the same time ! It simply does not make sense !
If you need to override behavior, you need inheritance !
If you want simplicity of call (one of the advantage of statics), you can use Factory (or singleton if only one instance is needed)
My guess is that you probably have to rethink your model. This set of constants of yours probably represent something that you could extract in a separate class then pass this class to your static method. Would that fit your needs ?
Edit
To your code sample:
public abstract static class Calculation
{
public static int Constant { get; set; }
public static int Calculate(int i) { return i * Constant; }
}
// ...
Calculation.Constant = 6;
Calculation.Calculate(123);
Somewhat more general:
public abstract static class Calculation
{
public struct Context
{
public int Constant, SignificantDigits;
public bool Radians;
}
public static int Calculate(int i, Context ctx) { return i * ctx.Constant; }
}
// ...
Calculation.Calculate(123, new Calculate.Context { Constant = 6 });
First idea:
The closest I can think of is generics:
public interface ISpecifics
{
void DoSomething();
string SomeProp { get; }
}
public static class Static<S>
where S : ISpecifics, new()
{
public static string ExerciseSpecific()
{
var spec = new S();
spec.DoSomething();
return spec.SomeProp;
}
}
Or if you really need a single static type
public static class Static
{
public static string ExerciseSpecific<S>()
where S : ISpecifics, new()
{
var spec = new S();
spec.DoSomething();
return spec.SomeProp;
}
}
Does that help?
I needed pretty much the same thing, so first I made a non-static class with all the functionality.
Then, a static class which instantiates one such non-static class in its static constructor.
Then any of the static methods calls the respective instance methods.
Something like this:
public class CalculationInstance
{
private int constant;
public int Calculate(int inputValue)
{
return inputValue * constant;
}
public void AnyOtherMethod()
{
....
}
public CalculationInstance(int constant)
{
this.constant=constant;
}
}
public static class Calculation
{
const int CONSTANT=2;
private CalculationInstance calc;
static Calculation()
{
calc=new CalculationInstance(CONSTANT);
}
public static int Calculate(int inputValue)
{
return calc.Calculate(inputValue);
}
public static void AnyOtherMethod()
{
calc.AnyOtherMethod();
}
}
static class Program
{
[STAThread]
static void Main()
{
//At some point:
int result = Calculation.Calculate(6);
}
}
I feel this doesn't make sense here, a static class is by default sealed class which means it is sealed for inheritance. So please don't consider having static with abstract.
You can have an abstract class and the child class can inherit and override the methods.

Overloading bitwise operator while using interface-based development

Using C# 3.0, .NET 3.5
I have a need for an enumeration that is a little smarter than a simple number. I have worked around this with static classes and properties, but one thing I am missing is the ability to use the enumeration like a bit flag without accessing a specfic properity.
For example this works:
public interface isomething
{
int value { get; }
}
public class something : isomething
{
public int value {get; private set;}
public somthing(int value)
{
this.value = value
}
public void DoSomething()
{
throw new NotImplementedException();
}
}
public static class SuperEnum
{
public static isomething first = new something(1);
public static isomething second= new something(2);
}
Then execute something like this:
Assert.IsTrue((SuperEnum.first.value | SuperEnum.second.value) == 3);
And you get a true. But if I add this to the something class:
public static int operator | (something leftSide, isomething rightside)
{
return leftside.value | rightside.value
}
Then execute something like this:
Assert.IsTrue((SuperEnum.first | SuperEnum.second) == 3);
I get a message that | operator can not used on the isomething type which sucks.
If I go with concrete types, I am fine, but that is going to cause problems in the future.
Anyone got any ideas?
Thanks, mark
I am not sure what you're trying to achieve. I think there is probably a better solution to the problem, but if the operator is important you can do it using an abstract class instead of interface:
public abstract class SomethingBase
{
protected int value;
protected SomethingBase(int value)
{
this.value = value;
}
public static int operator |(SomethingBase leftSide, SomethingBase rightside)
{
return leftSide.value | rightside.value;
}
}
public class Something : SomethingBase
{
public int Value
{
get { return value; }
}
public Something(int value) : base(value)
{
}
public void DoSomething()
{
throw new NotImplementedException();
}
}
Your issue comes from the fact that the ISomething interface doesn't declare the operator, and I'm not sure that you can make an operator a part of an interface contract. What sort of problems do you expect to be caused by using the concrete class?
If you are doing binary math, it sounds like you are talking about a value. If you are talking about a value, an immutable concrete type would be a good choice (perhaps a struct, depending on the size). And if you have a concrete type, you can add a bespoke operator.
Alternatively you could add an Or method to the interface (or add an extension method to do the same), but this may involve the first operand choosing the concrete type... but then, I'm not sure what the interface is adding anyway.

Categories