Search code examples
rider

JetBrains Rider - how to execute a C# scratch


In JetBrains Rider, when I create a scratch C# file, how can I execute it? Making the Main method public static and adding a namespace seems to be not enough.

Unable to find static method: MyNamespace.Foo.Main

using System;

namespace MyNamespace
{
    public class Foo
    {
        public static void Main()
        {
            Console.WriteLine("hello");
        }
    }
}

Rider version: JetBrains Rider 2022.3.1

Windows 10


Solution

  • Adding a namespace is actually not even required. What worked for me is the following:

    • creating a scratch file with the following content (as you already did):
    using System;
    
    class Foo
    {
        public void Main()
        {
            Console.WriteLine("hello");
        }
    }
    
    • then selecting the code you want to run/execute (ctrl+A for the entire script)
    • hit alt+enter to bring up a tooltip menu and select "Send Selection to C# Interactive" the tooltip menu can be seen in this image
    • this will open a C# interactive tab where you can input C# code such as var x = new Foo(); (and it doesn't matter if Rider does not recognise Foo() as a valid constructor), as can be seen in this image
    • lastly calling x.Main() will then run your function another image with the result when calling the function

    You can also find a good description on this page: https://blog.jetbrains.com/dotnet/2017/12/01/c-interactive-rider/

    I hope this helped!