2

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

izy
  • 1,085
  • 14
  • 18

1 Answers1

3

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!

Eonasdan
  • 7,563
  • 8
  • 55
  • 82
Tekbuildz
  • 46
  • 4
  • FYI: At the time of writing this comment, it is unfortunately not possible to use NuGet packages inside a scratch file... [This is the feature-request with state "Upvoting" as of writing this comment](https://youtrack.jetbrains.com/issue/RIDER-21806/Scratch-C-file-add-possibility-to-reference-project-assembly) – Tekbuildz Jul 16 '23 at 22:34