How can I implicitly convert another structure to my type?

Like this MyClass x = 120;, is it possible to create such a custom class? If so, how can I do this?

+3
source share
4 answers

It is generally considered a bad idea to use implicit operators, because they are, after all, implicit and work behind your back. Debugging code littered with operator overloads is a nightmare. However, 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 can use:

Complex complex = 10;

or you can overload 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;
+4
source

Create an implicit statement:

http://msdn.microsoft.com/en-us/library/z5z9kes2.aspx

For instance:

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 that a good idea?" is controversial. Implicit conversions tend to violate accepted standards for programmers; not a good idea at all. But if you are making some kind of library of great importance, for example, then this might be a good idea.

+3
source

yes, here is a brief 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); }
  }
+1
source

Source: https://habr.com/ru/post/1749417/


All Articles