Overloading assignment operator in C# - c#

I know the = operator can't be overloaded, but there must be a way to do what I want here:
I'm just creating classes to represent quantitative units, since I'm doing a bit of physics. Apparently I can't just inherit from a primitive, but I want my classes to behave exactly like primitives -- I just want them typed differently.
So I'd be able to go,
Velocity ms = 0;
ms = 17.4;
ms += 9.8;
etc.
I'm not sure how to do this. I figured I'd just write some classes like so:
class Power
{
private Double Value { get; set; }
//operator overloads for +, -, /, *, =, etc
}
But apparently I can't overload the assignment operator. Is there any way I can get this behavior?

It sounds like you should be using a struct rather than a class... and then creating an implicit conversion operator, as well as various operators for addition etc.
Here's some sample code:
public struct Velocity
{
private readonly double value;
public Velocity(double value)
{
this.value = value;
}
public static implicit operator Velocity(double value)
{
return new Velocity(value);
}
public static Velocity operator +(Velocity first, Velocity second)
{
return new Velocity(first.value + second.value);
}
public static Velocity operator -(Velocity first, Velocity second)
{
return new Velocity(first.value - second.value);
}
// TODO: Overload == and !=, implement IEquatable<T>, override
// Equals(object), GetHashCode and ToStrin
}
class Test
{
static void Main()
{
Velocity ms = 0;
ms = 17.4;
// The statement below will perform a conversion of 9.8 to Velocity,
// then call +(Velocity, Velocity)
ms += 9.8;
}
}
(As a side-note... I don't see how this really represents a velocity, as surely that needs a direction as well as a magnitude.)

You can create implicit conversion operators. There is a page on MSDN with a nice example.
It's also a good idea to make them immutable structs. That's exactly what the "primitives" are, and that's what makes it impossible to inherit from them. You want a struct because you want value-type semantics, instead of reference type semantics. And you want them immutable because mutable value types are generally a bad idea.

I think it cannot be overloaded because C# classes are all derived from Object, so they are basically objects, and when you use the assignment operators, you are basically just referencing another object. On the other hand, if you use a structure, then you basically need all the information, so when you use = operator, all fields will be copied.
So I would say, face it, and implement a function called Copy() and you should be fine :-)

Related

Can methods deny wrong types for Vector2 & Vector3

If i have a method:
public void SetPosition(Vector3 position){
// do stuff
}
And i pass a Vector2, why does it still allow it and auto convert this to be (x,y,0) ?
Is there any way to have the method be more strict and error and not auto convert the vectors? I keep doing this mistake once in a while without realising and get bugs that take me a while to work out the mistake.
Why does C# even allow the programmer to be able to do this when passing arguements?
I don't know what library defines Vector2 and Vector3 classes, but I expect there is an implicit conversion operator. This behavior has been implemented by the library that defines those classes.
One possible solution is to define a second Position method that accepts Vector2 and throws:
public void Position(Vector2 position){
throw new InvalidOperationException();
}
You cannot fix this, because the library that you are using supplies a conversion.
Unity defines an implicit conversion operator for Vector2 documented here:
Converts a Vector2 to a Vector3.
Vector2s can be implicitly converted to Vector3 (z is set to zero in the result).
This is consistent with your observation: the call to your method Position is done in two steps - first, Vector2 is converted to Vector3 with z set to zero, and then the result is passed to Position.
There is a trick that you can use to defeat the conversion operator, but it makes your code less readable, so I recommend against it. The idea is based on the fact that C# will not apply two implicit conversion operators to satisfy a method call, so you can do this:
class Vector3Wrap {
private readonly Vector3 v;
private Vector3Wrap(Vector3 v) {
this.v = v;
}
public static implicit operator Vector3Wrap(Vector3 v) {
return new Vector3Wrap(v);
}
public static implicit operator Vector3(Vector3Wrap w) {
return w.v;
}
}
public void SetPosition(Vector3Wrap positionWrap){
Vector3 position = positionWrap;
// do stuff
}
Now the call to SetPosition(myVector3) will succeed because Vector3Wrap will be created implicitly, but the call SetPosition(myVector2) will fail, because there is no implicit conversion from Vector2 to Vector3Wrap.
why does it still allow it and auto convert this to be (x,y,0) ?
The reason is that the author of the Vector2 struct wrote an implicit conversion to Vector3. Since this is part of the Unity3d engine, you can't really change that.
Is there any way to have the method be more strict and error and not auto convert the vectors?
There is no compiler option to turn implicit conversions off.
Why does C# even allow the programmer to be able to do this when passing arguements?
It allows the author of the type to define conversions that are "natural" that users don't want to have to think about. Now "natural" is a matter of perspective. I agree when you think they aren't natural they become very painful, so library authors have to be careful about them. There are guidelines for implicit conversions. Since it seems that Unity3d defines implicit conversion from Vector3 to Vector2 discarding the z component, they are not conforming to them, which is an unfortunate design decision. However this is not even the conversion you've got an issue with. Either way you are stuck with this library as it is.
If I really wanted to enforce that one should not haphazardly convert to Vector3, I would probably write some kind of wrapper type and use that. A very basic implementation would be
struct MyVector2
{
private Vector2 _value;
public MyVector2(Vector2 v)
{
_value = v;
}
public Vector2 Value { get { return _value; } }
public Vector3 ToVector3()
{
return Value;
}
public static implicit operator Vector2(MyVector2 v)
{
return v.Value;
}
}
So this wrapper would be around a Vector2. It would allow implicit conversion to Vector2 for use with whatever built in methods accept that, but to pass to a Vector3 you could use the ToVector3 method. Note that the Value is still implicitly convertible so be careful with it. Also this way you would not have to modify SetPosition in your example.
As said by others, implicit conversion can't be prevented as it's built into UnityEngine. However, you can still prevent bugs from this behavior by adding an overload of the method that accepts the unwanted type and throws an exception:
public void SetPosition(Vector3 position) {
// do stuff
}
public void SetPosition(Vector2 position) {
throw new System.Exception("Implicit conversion not allowed");
}
If you accidentally pass in a Vector2, the overload is automatically used because it's a better match, and you're notified about doing something that can lead to unexpected results.

How can I subtract two generic objects (T - T) in C# (Example: DateTime - DateTime)?

I wrote a Generic Class:
public class Interval<T> where T : IComparable // for checking that Start < End
{
public T Start { get; set; }
public T End { get; set; }
...
}
And I use this class with DateTime, int, etc.
I need a Duration property that returns a duration like:
public object Duration
{
get
{
return End - Start;
}
}
But when this property is included in my class, the compiler raises a logical error on the - operator.
What can I do to achieve this goal normally, or should I ignore it?
Try something like this:
static void Main(string[] args)
{
Tuple<int, bool> value = JustAMethod<int>(5, 3);
if (value.Item2)
{
Console.WriteLine(value.Item1);
}
else
{
Console.WriteLine("Can't substract.");
}
}
public static Tuple<T, bool> JustAMethod<T>(T arg1, T arg2)
{
dynamic dArg1 = (dynamic)arg1;
dynamic dArg2 = (dynamic)arg2;
dynamic ret;
try
{
ret = dArg1 - dArg2;
return new Tuple<T, bool>(ret, true);
}
catch
{
return new Tuple<T, bool>(default(T), false);
}
}
How this works: first, you convert the arguments to a dynamic type, and you can easily use operators on the dynamic type. If you wouldn't be able to use the operators, then an exception would be thrown at runtime. So, if you try to substract two objects that you actually can't substract, we'll catch the exception and return false as the second item in the Tuple.
This is not possible with generics in C# - at least not directly. It has been a highly requested feature on Connect for a long time.
You will need to make your types implement some interface that has a member that can be used, and constrain the class to that, or use one of the workarounds listed in the Connect bug (none of which are perfect), or a separate approach like MiscUtil's generic operators.
this work
public object Duration
{
get
{
return (dynamic)End - (dynamic)Start;
}
}
but no check, and slow
Check Jon Skeet's Misc Util https://jonskeet.uk/csharp/miscutil/
And here the generic operators by Marc Gravell: https://jonskeet.uk/csharp/miscutil/usage/genericoperators.html
The compiler does this so you don't write buggy code, its the whole point of generics and the concept of type safe programming.
If you need a method that subtracts dates write one that accepts a date, and if you need another one for integers, guess what you should write one for integers. Generics are not there so that the compiler can assume responsibility for any type. Think about it what if I wanted the difference between two objects, how would I do that with your generic method?
Or as #Reed Copsey mentioned you can constrain a class to it.
While this may seem like a major restriction, you need to remember that generics are generic. Of course, the System.Int32 type can work just fine with the binary operators of C#. However, for the sake of argument, if <T> were a custom class or structure type, the compiler cannot assume it has overloaded the +, -, *, and / operators.

Is it possible define an extension operator method?

is it possible to define an extension method that at the same time is an operator?
I want for a fixed class add the possibility to use a known operator that actually can't be applied.
For this particular case i want to do this:
somestring++; //i really know that this string contains a numeric value
And i don't want to spread types conversions for all the code.
I know that i could create wrapper class over an string and define that operator but i want to know if this kind of thing is possible to avoid search-and-replace every string declaration with MySpecialString.
Edited: as most have say string is sealed, so derivation isn't possible, so i modify "derived" to "wrapper", my mistake.
That is not possible in C#, but why not a standard extension method?
public static class StringExtensions {
public static string Increment(this string s) {
....
}
}
I think somestring.Increment() is even more readable, as you're not confusing people who really dont expect to see ++ applied to a string.
A clear example of where this would be useful is to be able to extend the TimeSpan class to include * and / operators.
This is what would ideally work...
public static class TimeSpanHelper
{
public static TimeSpan operator *(TimeSpan span, double factor)
{
return TimeSpan.FromMilliseconds(span.TotalMilliseconds * factor);
}
public static TimeSpan operator *(double factor, TimeSpan span) // * is commutative
{
return TimeSpan.FromMilliseconds(span.TotalMilliseconds * factor);
}
public static TimeSpan operator /(TimeSpan span, double sections)
{
return TimeSpan.FromMilliseconds(span.TotalMilliseconds / factor);
}
public static double operator /(TimeSpan span, TimeSpan period)
{
return span.TotalMilliseconds / period.TotalMilliseconds);
}
}
No, it is not possible to do from outside of the class. ++ operator should be defined inside class which is being incremented. You can either create your own class which will be convertible from string and will have ++ overload or you can forget about this idea and use regular methods.
No, you can't have an extension method which is also an operator. Extension methods can only be declared in static classes, which can't have instances and according to the C# spec,
User-defined operator declarations always require at least one of the parameters to be of the class or struct type that contains the operator declaration. [7.3.2]
Therefore, it is impossible for an extension method to also be an overloaded operator.
Additionally, you can't override System.String since it is a sealed class.
The string class is sealed in C#, so creating a string-derived class actually isn't possible.
That being said, an extension method will of course work just fine (as will a standard static method in a helper class) but it won't be an operator, just ordinarily-named method.
Currently this is not supported because Extension methods are defined in separate static class and static classes cannot have operator overloading definitions.
This is all true, but it would be nice for M$ to add this functionality in the future. Sometimes the framework is just missing things and an extension can help plug the gap (or fix the issue) this can sometimes be operators.
An example. To compare IP Addresses, you must use the Equals method to directly compare (of course parts of the struct could also be compared as could the address bytes individually - but that's another story). However, using the == operator always returns false at the object level (i.e. without converting them to strings etc). How hard is it to put the Equals method call inside the == operator call (that's rhetorical), but we can't do it. This is inconsistant and a place for bugs to creep in (note it does not fail, just always equates to false - whereas Equals does not).
I would argue that you should use a wrapper class, even if you could write an extension operator.
//i really know that this string contains a numeric value
is exactly the sort of situation that type-safety was invented for.
Another way of looking at it is that by writing that operator, you have broken many other functions and operators that work with the string class, since they don't necessarily preserve the property of containing a numeric value. By using a wrapper class, not a derived class, you only re-implement those features of string that make sense for numeric strings.
i was in a very similar situation as you described: i needed to increase the text (containing a numeric value for sure) in a Windows Forms textbox.
I understand your need as you described
somestring++; //i really know that this string contains a numeric value
My soultion is something like that which i believe is close to your description
somestring = (incrementable)somestring + 1
All i needed to do was
creating class called incrementable
defining an explicit operator in it (to aid converting string to incrementable )
defining an implicit operator in it (to aid converting incrementable back to string )
operator for + (plus sign)
Here's how my class looks in complete
public class incrementable
{
public string s; // For storing string value that holds the number
public incrementable(string _s)
{
s = _s;
}
public static explicit operator incrementable(string tmp)
{
return new incrementable(tmp);
}
public static implicit operator string(incrementable tmp)
{
return tmp.s;
}
public static incrementable operator +(incrementable str, int inc) // This will work flawlessly like `somestring = (incrementable)somestring + 1`
=> new incrementable((Convert.ToInt32(str.s) + inc).ToString());
public static incrementable operator ++(incrementable str) // Unfortunately won't work, see below
=> new incrementable((Convert.ToInt32(str.s) + 1).ToString());
}
Unfortunately i just couldn't get managed to improve my class by the usage of unary ++ operator. The reason against of usage of implicit conversion like ((incrementable)somestring)++ is that it is going to result in error saying The operand of an increment or decrement operator must be a variable, property or indexer hence can not be result of that casting.
Anyway, hope this helps!
As shown in the other answers, it cannot be done directly. But what if you need it, say you want to improve StringBuilder like
void Main()
{
var log = (StringBuilder)"Hello ";
log += "World!";
log += "\nThis example shows how to extend StringBuilder";
log.ToString().Dump();
}
how can you achieve this (i.e. use + operator instead of sb.Append(str);) ?
Answer:
In this case, you can't do it directly, but what you can do is:
Run it in DotNetFiddle
void Main()
{
var log = (StrBuilder)"Hello "; // same as: "Hello ".ToStrBuilder();
log += "World!";
log += "\nThis example shows how to extend StringBuilder";
log.ToString().Dump();
}
public static class Extensions
{
public static StrBuilder ToStrBuilder(this string str)
{
return new StrBuilder(str);
}
}
public class StrBuilder
{
private StringBuilder sb;
public StrBuilder()
{
sb = new StringBuilder();
}
public StrBuilder(string strB)
{
sb = new StringBuilder(strB);
}
public static implicit operator StrBuilder(string self)
{
return new StrBuilder(self);
}
public static StrBuilder operator +(StrBuilder sbA, string strB)
{
return sbA.Append(strB);
}
public StrBuilder Append(string strB)
{
sb.Append(strB);
return this;
}
public override string ToString()
{
return sb.ToString();
}
}
Note: You can't inherit from StringBuilder because it is a sealed class, but you can write a class that "boxes" a StringBuilder - which is, what is done here (thanks to IanNorton's answer regarding implicit conversion).

C# using the "this" keyword in this situation?

I've completed a OOP course assignment where I design and code a Complex Number class. For extra credit, I can do the following:
Add two complex numbers. The function will take one complex number object as a parameter and return a complex number object. When adding two complex numbers, the real part of the calling object is added to the real part of the complex number object passed as a parameter, and the imaginary part of the calling object is added to the imaginary part of the complex number object passed as a parameter.
Subtract two complex numbers. The
function will take one complex
number object as a parameter and
return a complex number object. When
subtracting two complex numbers, the
real part of the complex number
object passed as a parameter is
subtracted from the real part of the
calling object, and the imaginary
part of the complex number object
passed as a parameter is subtracted
from the imaginary part of the
calling object.
I have coded this up, and I used the this keyword to denote the current instance of the class, the code for my add method is below, and my subtract method looks similar:
public ComplexNumber Add(ComplexNumber c)
{
double realPartAdder = c.GetRealPart();
double complexPartAdder = c.GetComplexPart();
double realPartCaller = this.GetRealPart();
double complexPartCaller = this.GetComplexPart();
double finalRealPart = realPartCaller + realPartAdder;
double finalComplexPart = complexPartCaller + complexPartAdder;
ComplexNumber summedComplex = new ComplexNumber(finalRealPart, finalComplexPart);
return summedComplex;
}
My question is: Did I do this correctly and with good style? (using the this keyword)?
The use of the this keyword can be discussed, but it usually boils down to personal taste. In this case, while being redundant from a technical point of view, I personally think it adds clarity, so I would use it as well.
Use of the redundant this. is encouraged by the Microsoft coding standards as embodied in the StyleCop tool.
You can also to overload math operators, just like:
public static ComplexNumber operator +(ComplexNumber c1, ComplexNumber c2)
Since you're now learning C# and asking about style, I'm going to show you several things that are wrong with the code you posted along with reasons.
Edit: I only responded to this because it looks like you actually working to figure this stuff out. Since that's the type of people I prefer to work with, I'm more critical simply because I hope it helps you get somewhere better as a result. :)
Structure name
ComplexNumber is unnecessarily long. Note that none of Single, Double, Int32, Int64, etc. have Number in the name. This suggests Complex as a more appropriate name.
Complex matches the naming already established in the .NET Framework.
Real and imaginary components
GetRealPart() and GetComplexPart() should be get-only properties instead of methods.
GetComplexPart() is misnamed because it is actually returning the imaginary part.
Since the .NET framework already has a Complex structure, you shouldn't reinvent the naming. Therefore, unless you are in a position to redefine Framework conventions, the properties must be named Real and Imaginary.
Operations
If you look at existing examples like System.Windows.Vector, you see that math operations are implemented by providing a static method and an operator:
public static Point Add(Vector vector, Point point);
public static Point operator+(Vector vector, Point point);
Not surprisingly, this convention carried over to the System.Numerics.Complex structure:
public static Complex Add(Complex left, Complex right);
public static Complex operator +(Complex left, Complex right);
Summary
The result is clean, easy to verify, and behaves as everyone expects. The this keyword doesn't/can't appear because the methods are static.
public static Complex Add(Complex left, Complex right)
{
return new Complex(left.Real + right.Real, left.Imaginary + right.Imaginary);
}
public static Complex operator +(Complex left, Complex right)
{
return new Complex(left.Real + right.Real, left.Imaginary + right.Imaginary);
}
I use this keyword only for variables and when there's an argument that has the same name as the private variable. i.e.
private String firstname;
public SetName(String firstname)
{
this.firstname = firstname;
}
I would say yes, it looks correct and easy to read. But isn't this something your TA should answer?
double realPartCaller = this.GetRealPart();
Even if you omit this from GetRealPart() it should still be okay. But the use of this makes it quite easy to read and understand when it comes to maintainer.
double realPartCaller = this.GetRealPart(); ==> bit more readable IMHO
double realPartCaller = GetRealPart();
I find myself more and more using the this keyword for both methods and properties on the current instance, as I feel it increases readability and maintainability. this is especially useful if your class also has static methods and/or properties, on which you of course can not use the this keyword, as these are not related to the current instance. By using this, you clearly see the difference.
To bring it even further, you should consider using the class name as a qualifier for static methods and properties, even within the class itself.
Just to add completeness to the answers - there is one case when the this keyword is mandatory. That's when you have a local variable (or a method parameter) that has the same name as a class member. In this case writing it without this will access the local variable and with this will set the class member. To illustrate:
class MyClass
{
public int SomeVariable;
public void SomeMethod()
{
int SomeVariable;
SomeVariable = 4; // This assigns the local variable.
this.SomeVariable = 6; // This assigns the class member.
}
}
A couple things that follow from this:
Always avoid giving local variables the same name as class members (I admit, I don't always follow this myself);
Writing this in front of all member accesses acts like a safeguard. If you write a piece of code without it, and then later introduce a local variable with the same name and type as a class member, your code will still compile just fine, but will do something completely different (and probably wrong).
One instance though where I use the same names for method parameters as for class members is in constructors. I often write it like this:
class MyClass
{
public int VariableA;
public string VariableB;
public MyClass(int VariableA, string VariableB)
{
this.VariableA = VariableA;
this.VariableB = VariableB;
}
}
In my opinion this makes the constructor clearer, because you immediately understand which parameter sets which class member.
Usage of this keyword seems fine.
Though I believe for a class like Complex you should store the real and complex part as int properties and use them in the method, rather than using the methods GetRealPart() and GetComplexPart()
I would do it this way:
class ComplexNumber
{
public int RealPart { get; set; }
public int ComplexPart { get; set; }
public ComplexNumber(int real, int complex)
{
this.RealPart = real;
this.ComplexPart = complex;
}
public ComplexNumber Add(ComplexNumber c)
{
return new ComplexNumber(this.RealPart + c.RealPart, this.ComplexPart + c.ComplexPart);
}
}
The following is a scenario where this MUST be used, otherwise, the parameter and not the class member is considered for both LHS and RHS of the assignment.
public ComplexNumber(int RealPart, int ComplexPart)
{
RealPart = RealPart; // class member will not be assigned value of RealPart
ComplexPart = ComplexPart;
}
If you follow the naming conventions, using this is rearlly neded:
class MyClass
{
public int _variableA;
public string _variableB;
public MyClass(int variableA, string variableB)
{
_variableA = variableA;
_variableB = variableB;
}
}

Is there a C# generic constraint for "real number" types? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
C# generic constraint for only integers
Greets!
I'm attempting to set up a Cartesian coordinate system in C#, but I don't want to restrict myself to any one numerical type for my coordinate values. Sometimes they could be integers, and other times they could be rational numbers, depending on context.
This screams "generic class" to me, but I'm stumped as to how to constrict the type to both integrals and floating points. I can't seem to find a class that covers any concept of real numbers...
public class Point<T> where T : [SomeClassThatIncludesBothIntsandFloats?] {
T myX, myY;
public Point(T x, T y) {
myX = x;
myY = y;
}
}
Point<int> pInt = new Point<int>(5, -10);
Point<float> pFloat = new Point<float>(3.14159, -0.2357);
If I want this level of freedom, am I electing for a "typeof(T)" nightmare when it comes to calculations inside my classes, weeding out bools, strings, objects, etc? Or worse, am I electing to make a class for each type of number I want to work with, each with the same internal math formulae?
Any help would be appreciated. Thanks!
You can't define such a constraint, but you could check the type at runtime. That won't help you for doing calculations though.
If you want to do calculations, something like this would be an option:
class Calculations<T, S> where S: Calculator<T>, new()
{
Calculator<T> _calculator = new S();
public T Square(T a)
{
return _calculator.Multiply(a, a);
}
}
abstract class Calculator<T>
{
public abstract T Multiply(T a, T b);
}
class IntCalculator : Calculator<int>
{
public override int Multiply(int a, int b)
{
return a * b;
}
}
Likewise, define a FloatCalculator and any operations you need. It's not particularly fast, though faster than the C# 4.0 dynamic construct.
var calc = new Calculations<int, IntCalculator>();
var result = calc.Square(10);
A side-effect is that you will only be able to instantiate Calculator if the type you pass to it has a matching Calculator<T> implementation, so you don't have to do runtime type checking.
This is basically what Hejlsberg was referring to in this interview where the issue is discussed. Personally I would still like to see some kind of base type :)
This is a very common question; if you are using .NET 3.5, there is a lot of support for this in MiscUtil, via the Operator class, which supports inbuilt types and any custom types with operators (including "lifted" operators); in particular, this allows use with generics, for example:
public static T Sum<T>(this IEnumerable<T> source) {
T sum = Operator<T>.Zero;
foreach (T value in source) {
if (value != null) {
sum = Operator.Add(sum, value);
}
}
return sum;
}
Or for another example; Complex<T>
This is a known problem, since none of the arithmetic classes arrive from the same class. So you cannot restrict it.
The only thing you could do is
where T : struct
but thats not exactly what you want.
Here is a link to the specific issue.
Arithmetic types like int,double,decimal should implement IArithmetic<T>
You actually can do this, although the solution is tedious to set up, and can be confusing to devs who are not aware of why it was done. (so if you elect to do it document it thououghly!)...
Create two structs, called say, MyInt, and MyDecimal which act as facades to the CTS Int32, and Decimal core types (They contain an internal field of that respective type.) Each should have a ctor that takes an instance of the Core CTS type as input parameter..
Make each one implement an empty interface called INumeric
Then, in your generic methods, make the constraint based upon this interface.
Downside, everywhere you want to use these methods you have to construct an instance of the appropriate custom type instead of the Core CTS type, and pass the custom type to the method.
NOTE: coding the custom structs to properly emulate all the behavior of the core CTS types is the tedious part... You have to implement several built-in CLR interfaces (IComparable, etc.) and overload all the arithmetic, and boolean operators...
You can get closer with implementing few more
public class Point<T> where T : struct, IComparable, IFormattable, IConvertible,
IComparable<T>, IEquatable<T> {
}
The signature conforms to DateTime too. I'm not sure if you will be able to specify more types from the framework. Anyway this only solves part of the problem. To do basic numeric operations you will have to wrap your numeric types and use generic methods instead of standard operators. See this SO question for a few options.
This might be helpful. You have to use a generic class to achieve what you want.
C# doesn't currently allow type constraints on value types. i asked a related question not too long ago.
Enum type constraints in C#
Would this not lend itself to having seperate classes implementing IPoint?
Something like:
public interface IPoint<T>
{
T X { get; set; }
T Y { get; set; }
}
public class IntegerPoint : IPoint<int>
{
public int X { get; set; }
public int Y { get; set; }
}
As the calculations will have to differ in each implementation anyway right?
Dan#

Categories