5
2

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 5 years have passed since last update.

セミコロンレスC#

Last updated at Posted at 2018-05-08

セミコロンレスC#とは

Javaを習得している者として最早一般常識となりつつあるセミコロンレスJavaですが、
C#のそういう話題をあまり見ないなと思って少しだけ書いてみました。

Hello, World

Hello.cs
namespace SemicolonLess
{
    public class Program
    {
        public static void Main(string[] args)
        {
            if (Encoding.Default.GetBytes("Hello, Semicolon-Less world!\n") is var hellobytes &&
                Console.OpenStandardOutput().WriteAsync(hellobytes, 0, hellobytes.Length) == null){ }
        }
    }
}

変数の宣言

VarString.cs
if ("string" is var s) { }

変数の宣言は is 型パターンで行います。
できないだろうなと思ってvarにしたらコンパイル通ったのでびっくりしました
もちろん複数宣言したい場合は&で繋げればよいので、

VarString2.cs
if ("Hello" is var hello && "world" is var world) { }

ということになります。

標準出力

Console.WriteLineを使いたいところですが、Console.WriteLinevoid型なのでif文内部には使用できません。
なのでConsole.OpenStandardOutput()で標準出力を取ってきてWriteAsync()してやればできます。

値の加工

MultipleDouble.cs
if (1 is var x && (x = x * 2) != 1) { } //Intなので恐らく2倍して1になる数値はない

FizzBuzz

FizzBuzz.cs
namespace SemicolonLess
{
    public class Program
    {
        public static void Main(string[] args)
        {
            if (Enumerable.Range(1, 100)
                .Select(a => (a, (a % 3 == 0 ? "Fizz" : "") + (a % 5 == 0 ? "Buzz" : "")))
                .Select(b => (string.IsNullOrEmpty(b.Item2) ? b.a.ToString() : b.Item2) + "\n")
                .Select(Encoding.Default.GetBytes)
                .Select(c => Console.OpenStandardOutput().WriteAsync(c, 0, c.Length)).ToList() != null) { }
        }
    }
}

多分考えればもっと簡潔に書けると思いますが、とりあえずセミコロンレスにするだけした感じ。

結論

セミコロンC#がそんなになかったのはそれなりに理由があった

  • is型パターン
  • LINQ
  • Task

があればセミコロンがなくても大体のことはできる

5
2
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
5
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?