C# コンソールにテキストや実行結果を表示する

  • 作成日 2022.10.28
  • C#
C# コンソールにテキストや実行結果を表示する

C#で、コンソールにテキストや実行結果を表示するサンプルコードを記述してます「System.Console.WriteLine」か「System.Console.Write」を使用すると表示できます。「Debug.WriteLine」を使用すればデバッグウィンドウに出力することができます。

環境

  • OS windows11 pro 64bit
  • Microsoft Visual Studio Community 2022 Version 17.2.6

コンソールにテキストや実行結果を表示

コンソールにテキストや実行結果を表示するには、「System.Console.WriteLine」を使用します。

using System;

namespace ConsoleApp1
{
    internal class Program
    {
        static void Main(string[] args)
        {

            System.Console.WriteLine( 1 + 2 ); // 3

            System.Console.WriteLine( "text" ); // text


        }

    }
}

実行結果

「System.Console.Write」の場合は、改行がありません。

using System;

namespace ConsoleApp1
{
    internal class Program
    {
        static void Main(string[] args)
        {

            System.Console.Write( 1 + 2 ); // 3

            System.Console.Write( "text" ); // text

        }

    }
}

実行結果

改行する場合は「\r\n」を使用します。

using System;

namespace ConsoleApp1
{
    internal class Program
    {
        static void Main(string[] args)
        {            

            System.Console.Write("text\r\ntext");

        }

    }
}

実行結果

デバックウィンドウに出力

デバッグウィンドウに出力する場合は「Debug.WriteLine」または「Debug.Write」を使用します。

using System;
using System.Diagnostics;

namespace ConsoleApp1
{
    internal class Program
    {
        static void Main(string[] args)
        {

            Debug.WriteLine("text1");

            Debug.Write("text2\r\ntext3");

        }

    }
}

実行結果