Introduction
C# Scripting sounds odd!! Yes, it's true. We can execute C# as a scripting language. This can be achieved using csi.exe.
csi.exe is a command line interface to execute C# syntax like scripts. i.e. without class, method, Main method, we can execute C# commands.
When to use it?
It will play an important role when we want to test code snippets. There is no need to create any console or unit test project. Directly add the code snippet to the csi interface and press enter to see the result.
If you have installed Visual Studio, you will have csi.exe on your PC already on path: C:\Program Files\Microsoft Visual Studio\2022\Professional\MSBuild\Current\Bin\Roslyn\
We will try some scripts now
Open command prompt and switch to path C:\Program Files\Microsoft Visual Studio\2022\Professional\MSBuild\Current\Bin\Roslyn\ and try running commands like below.
You can write down code in a file and save it with csx extension, and execute it using the below command
For example, I will write the command below in a file and save it with name test.csx
//filename: test.csx
for (int index = 0; index < 10; index++)
{
Console.WriteLine($"Sample Value {index}");
}
List<string> list = new List<string>();
for (int index = 0; index < 10; index++)
{
list.Add($"List Index {index}");
}
Console.WriteLine();
Console.WriteLine("--------------------------");
Console.WriteLine();
foreach (string item in list)
{
Console.WriteLine(item);
}
To execute file use below command
#load <filepath>
After executing, we can see the below output
Summary
In this article, we understood using C# commands as scripting. I hope it will help you to check inline functions or small pieces of code to execute the test without any class/method main function.