0

I'm trying to recreate this in C#.

The problem i get is if i use constructors i MUST use new MyInt which i DO NOT WANT (to verbose). The way around it is to use the implicit/explicit operators. However they MUST be public... How the heck do i implement this in feature in C#?

The short question is i'd like to pass byte/short into a function but not int. Passing int should get me a compile error. I know i can easily get runtime with a public implicit int operator. The code below shows that int is automatically converted to char

Running sample shows true

using System;
class Program
{
        public static void Write(MyInt v)
        {
                Console.WriteLine("{0}", v.v is byte);
        }
        static void Main(string[] args)
        {
                Write(2);
        }
}
public struct MyInt
{
        public object v;
        public MyInt(byte vv) { v = vv; }
        public MyInt(short vv) { v = vv; }
        public MyInt(byte[] vv) { v = vv; }
        public static implicit operator MyInt(byte vv) { return new MyInt { v = vv }; }
        //public static extern implicit operator MyInt(int vv);
}

Heres more code which is useless. It implements MyInt2/MyInt which isn't required in the C++ solution

Community
  • 1
  • 1

1 Answers1

3

Just declare that your function takes short. Byte would be implicitly converted to short, but there is no implicit conversion from int to short, so int just won't pass

public class Class1
{
  public static void Aaa(short a)
  {

  }

  public void Bbb()
  {
    int i = 5;
    byte b = 1;
    short c = 1;
    Class1.Aaa(i); // Gives error
    Class1.Aaa(b); // Ok
    Class1.Aaa(c);  // ok
  }
}
Dmitry Osinovskiy
  • 9,999
  • 1
  • 47
  • 38
  • wow, weird. Unfortunately Aaa(1) still works. Hmmm, i'll post another question. Ok done http://stackoverflow.com/q/11432508/34537 –  Jul 11 '12 at 12:19