0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

C# implicit explicit

Last updated at Posted at 2020-01-20

implicit
暗黙のうちに変換。
宣言してもいい。

explicit
暗黙のうちに変換はできない。
明示的変換はできる。

使い方

public class Hoge
    {
        // intをhogeにしたとき
        public static implicit operator Hoge(int a) => new Hoge();
        // Hogeをintにしたとき
        public static implicit operator int(Hoge h) => 3;
    }

    private void Test()
    {
        Hoge h = new Hoge();
        // キャストする必要がない暗黙のうちに変換される。 しても良い。
        int i = h;
        h = i;
        i = h;
    }
public class Sample
{
    public class Hoge
    {
        // intをhogeにしたとき
        public static explicit operator Hoge(int a) => new Hoge();
        // Hogeをintにしたとき
        public static explicit operator int(Hoge h) => 3;
    }

    private void Test()
    {
        Hoge h = new Hoge();

        // int i = h; コンパイルエラー
        int i = (int)h; // OK

        // h = i コンパイルエラー
        h = (Hoge)i; // OK

        // i = h; コンパイルエラー
        i = (int)h // OK
    }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?