C#: same-signature methods/constructors and named arguments - c#

Suppose for instance I'm defining a Complex class for representing complex numbers. I would like to define two constructors, so that I can write for example:
Complex z1 = new Complex(x: 4, y: 3);
Complex z2 = new Complex(r: 2, theta: Math.PI / 4);
However, I cannot define the constructors like this:
public Complex(double x, double y) { ... }
public Complex(double r, double theta) { ... }
because both constructors would have the same signature, which is not allowed. But in C# 4 I can write this, using an optional argument:
public Complex(double x, double y) { ... }
public Complex(double r, double theta, bool unused=true) { ... }
It works, I can then use the above constructor calls as intended. The sole purpose of the unused argument is to make the signatures different; it's totally unused, both when defining and when calling the constructor.
To me this seems to be a an ugly trick: is there any better option?

Make the constructor private and have a static factory style function.
public static Complex CreateComplexPolar(double r, double theta);
public static Complex CreateComplex(double x, double y);
You can do validation on the inputs based on what they should be.
Another possibility would be to create a type that encapsulates the inputs and use constructors as you previously mentioned.
public struct PolarCoordinates
{
public double Rho;
public double Theta;
}
public struct CartesianCoordinates
{
public double X;
public double Y;
}
public Complex(PolarCoordinates pc);
public Complex(CartesianCoordinates cc);

Create a static method to create the class, say Complex::FromDouble and Complex::FromDoubleAndTheta.
You can go one step further and make the real constructor private in order to force that construction.
For example, see TimeSpan's FromDays and FromHours.
p.s.
Use better names :)
HTH

The only thing I can think of would be to make one constructor (double, double) and the other could be double, Func.
public Complex(double x, double y) { ... }
public Complex(double r, Func<double> theta) { ... }
It looks like in your example from above that you are doing a calculation and the result of that calculation is the 2nd value for that constructor. If that was always the case then you could just make it a Func parameter instead. Kind of a hack, but it might be better than having an optional 3rd parameter that does nothing.

Related

Understanding static implicit operator the right way

I had a brilliant thought, that does not seem to be so brilliant afterwards, but maybe I don't understand the whole thing correctly.
I have a class, that stores some numbers. Some other functions/methods need int's and some need double's. So I thought I can create a class with a precision conversion implicitly.
public class PreciseInteger
{
public double PreciseValue {get; private set;}
public int RoundedValue {get; private set;}
public PreciseInteger(double value)
{
PreciseValue = value;
RoundedValue = (int)Math.Round(value, 0, MidpointRounding.AwayFromZero);
}
public static implicit operator PreciseInteger(int number)
{
return new PreciseInteger(number);
}
public static implicit operator PreciseInteger(double number)
{
return new PreciseInteger(number);
}
public static implicit operator int(PreciseInteger number)
{
return number.RoundedValue;
}
public static implicit operator double(PreciseInteger number)
{
return number.PreciseValue;
}
public override string ToString()
{
return PreciseValue.ToString();
}
}
And the class that uses this class is really a simple property storing class that does not much. So now I use somthing like
double myValue = myClass.StoredValue1 / myDivider;
But here I only get the integer value. I don't want to use an explicit casting (like Convert.ToDouble or (double)). So how could I make sure that the precise value is used and not the rounded one? Or did I misunderstand the whole concept and that doesn't work at all and I would have to use something like MyClass.MyDouble and MyClass.MyInteger values?
Edit: Ok, if I first say int newInt = myClass.StoredValue1 I get a rounded integer and if I use double newDouble = myClass.StoredValue1 I get the precise floating point number. But isn't there a way to say that one of them is always preferred?
The / operator is defined for both int and double:
double operator /(double x, double y);
int operator /(int x, int y);
These two overloads are both applicable when you do:
// assuming myClass.StoredValue1 and myDivider are PreciseIntegers
double myValue = myClass.StoredValue1 / myDivider;
because you defined an implicit conversion to int and an implicit conversion to double. However, the / that takes ints is actually a better function member, because int is a better conversion target, so the compiler always chooses the second overload.
One way to work around this is to define your own / operator for PreciseInteger:
public static PreciseInteger operator /(PreciseInteger number1, PreciseInteger number2) {
return number1.PreciseValue / number2.PreciseValue;
}
Then you can do:
double myValue = myClass.StoredValue1 / myDivider;

Passing unconstrained generic type parameter to a constrained method

I have too methods:
public TValueType? DoStuffWithValueType<TValueType>(int x, int y)
where TValueType: struct {}
public TRefType DoStuffWithRefType<TRefType>(int x, int y)
where TRefType: class {}
How can i wrap them in a new third method?
The following is not compiling since i cannot persuade the compiler that T is in fact a struct when calling DoStuffWithValueType:
public T DoStuff<T>(int x, int y) {
if(typeof(T).IsValueType)
{
return DoStuffWithValueType<T>(x, y);
}
return DoStuffWithRefType<T>(x, y);
}
I already tried overloading DoStuff, but this attempt failed since generic-constraints are not part of the method signature.I also tried to get rid of the constraints, but i could not.
Any ideas? Thank you!
You can't, basically - you'd have to invoke the relevant methods with reflection, which is ugly.
Of course you can do this with dynamic typing, which hides the reflection from you:
public T DoStuff<T>(int x, int y) {
dynamic d = this;
if(typeof(T).IsValueType)
{
return d.DoStuffWithValueType<T>(x, y);
}
return d.DoStuffWithRefType<T>(x, y);
}
You may think that's cleaner than doing it manually with reflection - or you may not :)
There's no way that I'm aware of to make the compiler "trust" a type argument where it wouldn't normally do so.
Aside from Jon Skeet's use of dynamic, the cleanest way I can think of, minimising the required reflection, and so keeping as much verified by the compiler as possible, is to call the method through a helper class.
abstract class DoStuffHelper<T> {
public abstract T DoStuff(int x, int y);
}
class DoStuffWithValueTypeHelper<T> : DoStuffHelper<T> where T : struct {
public override T DoStuff(int x, int y) {
return DoStuffWithValueType<T>(x, y);
}
}
class DoStuffWithRefTypeHelper<T> : DoStuffHelper<T> where T : class {
public override T DoStuff(int x, int y) {
return DoStuffWithRefType<T>(x, y);
}
}
public T DoStuff<T>(int x, int y) {
DoStuffHelper<T> helper;
Type helperType;
if(typeof(T).IsValueType)
helperType = typeof(DoStuffWithValueTypeHelper<>);
else
helperType = typeof(DoStuffWithRefTypeHelper<>);
helperType = helperType.MakeGenericType(typeof(T));
helper = (DoStuffHelper<T>)Activator.CreateInstance(helperType);
return helper.DoStuff(x, y);
}
If appropriate for your situation, you can cache the helper classes in a Dictionary<Type, object> to avoid re-creating them every time.

c# how to passing functions as string to methods

Is it possible to pass a function (like let's say sin() ) via string and then use it as int?
Like: (main idea only)
public int getfunc(String func)
{
return res_of(func)
}
I tried playing around with string of "Math.sin(0)"
but couldn't print the 0...
I could predefine the math functions since I only need 1 and then it becomes extremely simple as I only pass the int value for the function to work on, but I thought may-hap there is a way to keep it more generic.
I do not want to use mapping of the functions I want to keep it dynamic....
is ther a way of doing so?
I'd like to offer an alternative approach that you may not have considered.
You could use a delegate instead of passing a string; that way, you won't need any reflection.
There's a predefined delegate type in C# called Func<> which lets you easily define the return type and parameter types of a method that you want to pass as a delegate.
For example, the Func<> for Math.Sin(double) would be Func<double, double> because Math.Sin() returns a double and takes a double parameter.
An example will make this clearer:
using System;
namespace Demo
{
internal class Program
{
private void run()
{
Func<double, double> f1 = Math.Sin;
Func<double, double> f2 = Math.Cos;
double r1 = runFunc(f1, 1.0);
double r2 = runFunc(f2, 2.0);
Console.WriteLine(r1);
Console.WriteLine(r2);
}
private static double runFunc(Func<double, double> func, double parameter)
{
return func(parameter);
}
private static void Main()
{
new Program().run();
}
}
}
Try using http://www.csscript.net/
dynamic script = CSScript.Evaluator
.LoadCode(#"using System;
public class Script
{
public int Sum(int a, int b)
{
return a+b;
}
}");
int result = script.Sum(1, 2);
Declare the method like this:
public int DoCalculation(Func<double, double> func, double a)
{
return Convert.ToInt32(func(a));
}
Then use it like this:
int result = DoCalculation(Math.Sin, 3.3);
In our application we use the .NET integrated C# compiler.
This is some work to do but straight-forward to implement.
Here's an answer with a lot more details on that.
We use this in our companies production.

Concise, fast singleton subclasses

I'm writing, in C#, an interpreter for a dynamic language, and implementing primitive functions as an abstract class Primitive with a virtual Apply method, where each actual primitive function will be a subclass that overrides Apply.
(An alternative would be to only have the class Primitive and store a function pointer for Apply. However, making it a virtual method seems likely to be slightly faster, and this code will be run very frequently, so a small speedup is worth having.)
Obviously I could go ahead and create a full-blown class file for each primitive function, but I can't help feeling there ought to be a slightly more concise way of doing things than creating dozens of tiny class files.
In Java I'd use the anonymous subclass syntax to create and instantiate a subclass all in one expression, but I don't think C# has an exact counterpart.
What is the best way of doing this in C#?
Firstly, I wouldn't assume that a virtual method call will be faster than a delegate. Maybe it will, maybe it won't - but if performance is really that important to you, you should measure that. It would be really simple to code this using lambda expressions, particularly if all you're trying to represent is a function:
public static readonly Func<int, int> Addition = (x, y) => x + y;
public static readonly Func<int, int> Subtraction = (x, y) => x - y;
// etc
(I'm just guessing at the sorts of operation here, as we don't know the details.)
There's no particularly tiny syntax for subclasses in C#, but for semi-singletons like this
I find nested classes work well... similar to Java enums:
public abstract class Primitive
{
public static readonly Primitive Addition = new AdditionPrimitive();
public static readonly Primitive Subtraction = new SubtractionPrimitive();
// Prevent outside instantiation
private Primitive()
{
}
public abstract int Apply(int x, int y);
// Anything else you want
private class AdditionPrimitive : Primitive
{
public override int Apply(int x, int y)
{
return x + y;
}
}
private class SubtractionPrimitive : Primitive
{
public override int Apply(int x, int y)
{
return x - y;
}
}
}

What is the best way to attach static methods to classes rather than to instances of a class?

If I have a method for calculating the greatest common divisor of two integers as:
public static int GCD(int a, int b)
{
return b == 0 ? a : GCD(b, a % b);
}
What would be the best way to attach that to the System.Math class?
Here are the three ways I have come up with:
public static int GCD(this int a, int b)
{
return b == 0 ? a : b.GCD(a % b);
}
// Lame...
var gcd = a.GCD(b);
and:
public static class RationalMath
{
public static int GCD(int a, int b)
{
return b == 0 ? a : GCD(b, a % b);
}
}
// Lame...
var gcd = RationalMath.GCD(a, b);
and:
public static int GCD(this Type math, int a, int b)
{
return b == 0 ? a : typeof(Math).GCD(b, a % b);
}
// Neat?
var gcd = typeof(Math).GCD(a, b);
The desired syntax is Math.GCD since that is the standard for all mathematical functions.
Any suggestions? What should I do to get the desired syntax?
You cannot. Extension methods are just syntactic sugar for calling a static function and passing an instance of a particular type. Given that, they operate only on instances, as they must be defined by passing a this parameter of the type you want to attach to.
I would prefer the one with RationalMath. You really don't need extension methods here, because their aim is to mimic instance methods of objects of you can't modify. But here one should use plain old static method.
Given the fact that you cannot extend the static Math class I would go for sample #2. It follows the pattern used by Math, does not clutter the int method space, and is simple and clean to invoke. #3 is plain horrible :)
Personally, I wouldn't do it the way you want. System.Math is just one static class that contains some mathematical functions . . . there's no reason it has to contain every mathematical function you'd ever want to use.
However, if you really want this, I suppose you could write your own static Math class that's a sort of wrapper for System.Math . . . basically just implement every function in System.Math by passing it along to the actual System.Math class. Like this:
public static class Math
{
public static int GCD(int a, int b)
{
return b == 0 ? a : GCD(b, a % b);
}
// Implement the System.Math methods
public static double Pow(double x, double y)
{
return System.Math.Pow(x, y);
}
// etc.
}
This seems like a real pain in the neck though for not much benefit. (Kind of an anti-syntactic sugar.) But it would let you call Math.GCD(a,b) and, say, Math.Pow(x,y) from the same class, which is what it sounds like you want.
Ok, one other way I thought of:
namespace My
{
public static class Math
{
}
}
namespace MainApp
{
...
var gcd = My.Math.GCD(a, b);
...
}

Categories