Hello,
As it is MyClass x = 120;
, is it possible to create such a custom class?
If so, how can I do that?
Hello,
As it is MyClass x = 120;
, is it possible to create such a custom class?
If so, how can I do that?
Not sure if this is what you want but you may get there by implementing the implicit operator: http://msdn.microsoft.com/en-us/library/z5z9kes2(VS.71).aspx
Create an implicit operator:
http://msdn.microsoft.com/en-us/library/z5z9kes2.aspx
For example:
public struct MyStruct // I assume this is what you meant, since you mention struct in your title, but use MyClass in your example.
{
public MyClass(int i) { val = i; }
public int val;
// ...other members
// User-defined conversion from MyStruct to double
public static implicit operator int(MyStruct i)
{
return i.val;
}
// User-defined conversion from double to Digit
public static implicit operator MyStruct(int i)
{
return new MyStruct(i);
}
}
"Is this a good idea?" is debatable. Implicit conversions tend to break accepted standards for programmers; generally not a good idea. But if you're doing some large value library, for example, then it might be a good idea.
yes, here's a short example ...
public struct MyCustomInteger
{
private int val;
private bool isDef;
public bool HasValue { get { return isDef; } }
public int Value { return val; } }
private MyCustomInteger() { }
private MyCustomInteger(int intVal)
{ val = intVal; isDef = true; }
public static MyCustomInteger Make(int intVal)
{ return new MyCustomInteger(intVal); }
public static NullInt = new MyCustomInteger();
public static explicit operator int (MyCustomInteger val)
{
if (!HasValue) throw new ArgumentNullEception();
return Value;
}
public static implicit operator MyCustomInteger (int val)
{ return new MyCustomInteger(val); }
}
It's generally considered a bad idea to use implicit operators, as they are, after all, implicit and run behind your back. Debugging code littered with operator overloads is a nightmare. That said, with something like this:
public class Complex
{
public int Real { get; set; }
public int Imaginary { get; set; }
public static implicit operator Complex(int value)
{
Complex x = new Complex();
x.Real = value;
return x;
}
}
you could use:
Complex complex = 10;
or you could ever overload the + operator
public static Complex operator +(Complex cmp, int value)
{
Complex x = new Complex();
x.Real = cmp.Real + value;
x.Imaginary = cmp.Imaginary;
return x;
}
and use code like
complex +=5;