public class Faranheit
{
public float Digree { get; set; }
public Faranheit(float f)
{
Digree = f;
}
public static implicit operator Celcius(Faranheit f)
{
return new Celcius((5.0f / 9.0f) * (f.Digree - 32));
}
public static implicit operator Faranheit(Celcius c)
{
return new Faranheit((9.0f / 5.0f) * c.Digree + 32);
}
}
public class Celcius
{
public float Digree{get;set;}
public Celcius(float c)
{
Digree = c;
}
}
I am just confused, where to put the conversion methods exactly..
It works fine even if I put one method in one class and other in the other, or I interchange them or even if I put both of them in any of the two classes..
But if I put it outside these two classes it doesn't work (compile error)..
Could please someone put some light on this..
EDIT:
if it allows the conversion methods to be in either of the class, why doesn't it allow the conversion method to be in a separate class??
All that matters is that the implicit conversion exists in one of the two classes. I would tend to put both conversions in the less-commonly used class.
In this case, the classes look equal, so I would put the conversion to the class in each class i.e. the conversion from F to C would go in the Celsius class, and vice versa.
Really, it's mostly about personal preference.
In this specific case, I would write a Temperature class that lets you get the temperature in C, F, K, R, etc. But that isn't exactly relevant to the actual question.
I would put them in each of the classes. So you can do stuff like:
Celsius c = new Celsius(Value);
Fahrenheit f = c.toFahrenheit();
Celsius newC = f.toCelsius();
edit: or if you wanted to go the Helper class route, you could do:
public static class ConvertTemps
{
public static Celsius toCelsius(Fahrenheit F)
{
return new Celsius(5/8* F - 32);
}
public static Fahrenheit toFahrenheit(Celsius C)
{
return new Fahrenheit(8/5*C + 32);
}
}
and then you could do things like:
Celsius c = new Celsius(value);
Fahrenheit f = ConvertTemps.toFahrenheit(c);
But I'd go the first route.
Related
I would like to add some functions to double type. I created new class "ExtraDouble" and I I want to class behave as double.
For example: I have:
class ExtraDouble{
double myVar = 0.59;
}
And, wherever:
Extradouble e = new Extradouble();
String.Format("Value of e is: {0}", e) // return: Value of e is: 0.59
Is it possible?
Default using "e" must return value of variable "myVar" (without any accessors)
Yes. All objects have a virtual ToString method. For your case, just override that:
class ExtraDouble
{
double myVar = 0.59;
public override string ToString()
{
return myVar.ToString();
}
}
For more completeness. If you want your ExtraDouble to behave as a double in common scenarios (like performing arithmetic operations), you can use the implicit keyword:
class ExtraDouble : Object
{
double myVar = 0.59;
public override string ToString()
{
return myVar.ToString();
}
public static implicit operator double(ExtraDouble d)
{
return d.myVar;
}
}
Then you can do things like:
Console.WriteLine(5 * new ExtraDouble());
If I understand you question correctly, you want to class that behaves like a double but with extended functionality. You could take a look at object extensions. They are designed to extend classes that you do not normally have access to inherit.
public static class DoubleExtension
{
public static double Sqr(this double d)
{
return d * d;
}
}
This will make it look like the Sqr() is a method of the type double.
E.g.
double d = 2.0f;
double sqrD = d.Sqr();
// This value will now be 4. This call looks like a class method but its not, it's an extension
This question already has answers here:
Is there a C# generic constraint for "real number" types? [duplicate]
(8 answers)
Closed 9 years ago.
I'm trying to make structure that represent four-dimensional vector.
I made something like this:
struct Vector4D<T>
{
public T v1;
public T v2;
public T v3;
public T v4;
//...
public static Vector4D<T> operator *(Vector4D<T> a, T b)
{
a.v1 *= b;
a.v2 *= b;
a.v3 *= b;
a.v4 *= b;
return a;
}
}
Well, this structure dosen't make sense if T isn't any numeric type like Int32, Int64, Double, Single, Decimal etc...
So, my question is how can I constrain T to be only one of following types, Int16, Int32, Int64, UInt16, UInt32, UInt64, Byte, SByte, Single, Double, Decimal?
I was trying do something like this
struct Vector4D<T> where T : Int16, Int32, Int64 // and so go on
{
//....
}
But it didn't work.
You do have to explicitly write a multiply method for each type.
However, you can simplify things a bit as this compilable code sample shows:
using System;
namespace Demo
{
internal class Program
{
static void Main()
{
var d = new Vector4D<double>{v1=1, v2=2, v3=3, v4=4};
Console.WriteLine(d*2); // Prints 2, 4, 6, 8
var i = new Vector4D<int>{v1=1, v2=2, v3=3, v4=4};
Console.WriteLine(i*2); // Prints 2, 4, 6, 8
// This will throw a "NotSupported" exception:
var s = new Vector4D<string>{v1="1", v2="2", v3="3", v4="4"};
Console.WriteLine(s*"");
}
}
partial struct Vector4D<T>
{
public T v1;
public T v2;
public T v3;
public T v4;
public static Vector4D<T> operator *(Vector4D<T> a, T b)
{
a.v1 = multiply(a.v1, b);
a.v2 = multiply(a.v2, b);
a.v3 = multiply(a.v3, b);
a.v4 = multiply(a.v4, b);
return a;
}
public override string ToString()
{
return string.Format("v1: {0}, v2: {1}, v3: {2}, v4: {3}", v1, v2, v3, v4);
}
private static Func<T, T, T> multiply;
}
// Partial just to keep this logic separate.
partial struct Vector4D<T>
{
static Vector4D() // Called only once for each T.
{
if (typeof(T) == typeof(int))
Vector4D<int>.multiply = (a, b) => a*b;
else if (typeof(T) == typeof(double))
Vector4D<double>.multiply = (a, b) => a*b;
else if (typeof(T) == typeof(float))
Vector4D<float>.multiply = (a, b) => a*b;
else
multiply = (a, b) =>
{
string message = string.Format("Vector4D<{0}> not supported.", typeof(T));
throw new NotSupportedException(message);
};
}
}
}
That way, you can put all the multiply (and presumably divide, add and subtract) logic into the second partial struct and keep it all separate from the main logic.
The second partial struct only contains a static type constructor which will be called once only (per assembly domain) for each type T which is used to create a struct.
You do have the overhead of querying the type, but it is only once per run of the program and I guess the overhead would be pretty low.
Also, you don't have to use a partial struct at all - you can just put the static type constructor with the rest of the struct implementation. I only separated it out as an example, because it is purely initialisation logic which you could consider separately from the rest of the struct's logic.
Important Note that if you use the Vector4D with a type for which you haven't defined a multiply operation, you'll get the NotSupportedException defined in static Vector4D(). This does at least tell you exactly what is wrong, along the lines of:
Unhandled Exception: System.NotSupportedException: Vector4D<System.String> not supported.
You cannot do this, not this way.
C# does not know anyhting about generic type T. Is it a number? Is it a string? Can you do math with it?
If you want to get this working, you have to use a generic calculator. You must build it yourself. For more info, take a look at: http://www.codeproject.com/Articles/8531/Using-generics-for-calculations
A simpler solution could be:
a.v1 = Convert.ChangeType(Convert.ToDecimal(a.v1) * Convert.ToDecimal(b), typeof(T));
EDIT
I created a few library functions on another location. You can use this to implement in your own code. Calculating with these numbers would be easy. Your Vector-class would be:
partial struct Vector4D<T>
where T: IComparable<T>, IEquatable<T>
{
public Number<T> v1;
public Number<T> v2;
public Number<T> v3;
public Number<T> v4;
public static Vector4D<T> operator *(Vector4D<T> a, T b)
{
a.v1 *= b;
a.v2 *= b;
a.v3 *= b;
a.v4 *= b;
return a;
}
}
See: https://codereview.stackexchange.com/questions/26022/improvement-requested-for-generic-calculator-and-generic-number
Can I create a class with a default return value? Lets say if I create an object of this class I get always a specific value, without calling the properties or something else. Example:
int i = new MyIntClass(/*something*/); //will return an int
Actually I would like to use a default function for returning something. Maybe like this:
class MyCalculator()
{
public double a { get; set; }
public double b { get; set; }
MyCalculator(double a, double b)
{
this.a = a;
this.b = b;
}
public double DoMath()
{
return a*b;
}
}
/* somewhere else */
double result = new MyCalculator(5.5, 8.7);
result should be the result of DoMath(). Is that possible? I know its maybe not the best example, but something like this would be nice. Any ideas?
You can do an implicit cast.
Example (add to class):
public static implicit operator double(MyCalculator c)
{
return c.DoMath();
}
If I follow you, you want a MyCalculator to have a double it can be treated as. You can do this with an implicit cast operator overload. Put this in the definition of MyCalculator:
public static implicit operator double(MyCalculator m)
{
return m.DoMath();
}
However, it somewhat hides what's going on (you called new and got a double) and if you're a heavy user of var you'll find it annoying because you have to then be explicit.
In all, only use implicit if you have a very strong justification for it. Indeed, only use explicit if you have a very strong justification for it, and only use implicit if you've an extremely strong justification.
A good guideline for anything to do with a class' interface is "how sensible or weird will this look to someone who never sees the source code?"
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);
...
}
Is there any feasible way of using generics to create a Math library that does not depend on the base type chosen to store data?
In other words, let's assume I want to write a Fraction class. The fraction can be represented by two ints or two doubles or whatnot. The important thing is that the basic four arithmetic operations are well defined. So, I would like to be able to write Fraction<int> frac = new Fraction<int>(1,2) and/or Fraction<double> frac = new Fraction<double>(0.1, 1.0).
Unfortunately there is no interface representing the four basic operations (+,-,*,/). Has anybody found a workable, feasible way of implementing this?
Here is a way to abstract out the operators that is relatively painless.
abstract class MathProvider<T>
{
public abstract T Divide(T a, T b);
public abstract T Multiply(T a, T b);
public abstract T Add(T a, T b);
public abstract T Negate(T a);
public virtual T Subtract(T a, T b)
{
return Add(a, Negate(b));
}
}
class DoubleMathProvider : MathProvider<double>
{
public override double Divide(double a, double b)
{
return a / b;
}
public override double Multiply(double a, double b)
{
return a * b;
}
public override double Add(double a, double b)
{
return a + b;
}
public override double Negate(double a)
{
return -a;
}
}
class IntMathProvider : MathProvider<int>
{
public override int Divide(int a, int b)
{
return a / b;
}
public override int Multiply(int a, int b)
{
return a * b;
}
public override int Add(int a, int b)
{
return a + b;
}
public override int Negate(int a)
{
return -a;
}
}
class Fraction<T>
{
static MathProvider<T> _math;
// Notice this is a type constructor. It gets run the first time a
// variable of a specific type is declared for use.
// Having _math static reduces overhead.
static Fraction()
{
// This part of the code might be cleaner by once
// using reflection and finding all the implementors of
// MathProvider and assigning the instance by the one that
// matches T.
if (typeof(T) == typeof(double))
_math = new DoubleMathProvider() as MathProvider<T>;
else if (typeof(T) == typeof(int))
_math = new IntMathProvider() as MathProvider<T>;
// ... assign other options here.
if (_math == null)
throw new InvalidOperationException(
"Type " + typeof(T).ToString() + " is not supported by Fraction.");
}
// Immutable impementations are better.
public T Numerator { get; private set; }
public T Denominator { get; private set; }
public Fraction(T numerator, T denominator)
{
// We would want this to be reduced to simpilest terms.
// For that we would need GCD, abs, and remainder operations
// defined for each math provider.
Numerator = numerator;
Denominator = denominator;
}
public static Fraction<T> operator +(Fraction<T> a, Fraction<T> b)
{
return new Fraction<T>(
_math.Add(
_math.Multiply(a.Numerator, b.Denominator),
_math.Multiply(b.Numerator, a.Denominator)),
_math.Multiply(a.Denominator, b.Denominator));
}
public static Fraction<T> operator -(Fraction<T> a, Fraction<T> b)
{
return new Fraction<T>(
_math.Subtract(
_math.Multiply(a.Numerator, b.Denominator),
_math.Multiply(b.Numerator, a.Denominator)),
_math.Multiply(a.Denominator, b.Denominator));
}
public static Fraction<T> operator /(Fraction<T> a, Fraction<T> b)
{
return new Fraction<T>(
_math.Multiply(a.Numerator, b.Denominator),
_math.Multiply(a.Denominator, b.Numerator));
}
// ... other operators would follow.
}
If you fail to implement a type that you use, you will get a failure at runtime instead of at compile time (that is bad). The definition of the MathProvider<T> implementations is always going to be the same (also bad). I would suggest that you just avoid doing this in C# and use F# or some other language better suited to this level of abstraction.
Edit: Fixed definitions of add and subtract for Fraction<T>.
Another interesting and simple thing to do is implement a MathProvider that operates on an abstract syntax tree. This idea immediately points to doing things like automatic differentiation: http://conal.net/papers/beautiful-differentiation/
I believe this answers your question:
http://www.codeproject.com/KB/cs/genericnumerics.aspx
Here's a subtle problem that comes with generic types. Suppose an algorithm involves division, say Gaussian elimination to solve a system of equations. If you pass in integers, you'll get a wrong answer because you'll carry out integer division. But if you pass in double arguments that happen have integer values, you'll get the right answer.
The same thing happens with square roots, as in Cholesky factorization. Factoring an integer matrix will go wrong, whereas factoring a matrix of doubles that happen to have integer values will be fine.
First, your class should limit the generic parameter to primitives ( public class Fraction where T : struct, new() ).
Second, you'll probably need to create implicit cast overloads so you can handle casting from one type to another without the compiler crying.
Third, you can overload the four basic operators as well to make the interface more flexible when combining fractions of different types.
Lastly, you have to consider how you are handling arithmetic over and underflows. A good library is going to be extremely explicit in how it handles overflows; otherwise you cannot trust the outcome of operations of different fraction types.
The other approaches here will work, but they have a high performance impact over raw operators. I figured I would post this here for someone who needs the fastest, not the prettiest approach.
If you want to do generic math without paying a performance penalty, then this is, unfortunately, the way to do it:
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static T IncrementToMax(T value)
{
if (typeof(T) == typeof(char))
return (char)(object)value! < char.MaxValue ? (T)(object)(char)((char)(object)value + 1) : value;
if (typeof(T) == typeof(byte))
return (byte)(object)value! < byte.MaxValue ? (T)(object)(byte)((byte)(object)value + 1) : value;
// ...rest of the types
}
It looks horrific, I know, but using this method will produce code that runs as fast as possible. The JIT will optimize out all the casts and conditional branches.
You can read the explanation and some additional important details here: http://www.singulink.com/codeindex/post/generic-math-at-raw-operator-speed
.NET 7 introduces a new feature - generic math (read more here and here) which is based on addition of static abstract interface methods. This feature introduces a lot of interfaces which allow to generically abstract over number types and/or math operations:
class Fraction<T> :
IAdditionOperators<Fraction<T>, Fraction<T>, Fraction<T>>,
ISubtractionOperators<Fraction<T>, Fraction<T>, Fraction<T>>,
IDivisionOperators<Fraction<T>, Fraction<T>, Fraction<T>>
where T : INumber<T>
{
public T Numerator { get; }
public T Denominator { get; }
public Fraction(T numerator, T denominator)
{
Numerator = numerator;
Denominator = denominator;
}
public static Fraction<T> operator +(Fraction<T> left, Fraction<T> right) =>
new(left.Numerator * right.Denominator + right.Numerator * left.Denominator,
left.Denominator * right.Denominator);
public static Fraction<T> operator -(Fraction<T> left, Fraction<T> right) =>
new(left.Numerator * right.Denominator - right.Numerator * left.Denominator,
left.Denominator * right.Denominator);
public static Fraction<T> operator /(Fraction<T> left, Fraction<T> right) =>
new(left.Numerator * right.Denominator, left.Denominator * right.Numerator);
}