4

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

CC BY-SA 4.0
0

2 Answers 2

6

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!

CC BY-SA 4.0
1
1

My two cents, if you simply want to quickly run your scratch from the terminal (inspired by dotnet-script answer):

  1. Open the Rider terminal.
  2. Firstly, install dotnet-script if you haven't done so yet (just run dotnet tool install -g dotnet-script).
  3. Right-click on your scratch tab -> Copy Path/Reference... -> Absolute Path.
  4. In the Rider's terminal, run dotnet script "<HERE PASTE THE COPIER ABSOLUTE PATH>".

For example: enter image description here

You can then also create a new configuration to run your scratch, and quickly test your code.

CC BY-SA 4.0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.