Scripting with C#


Have you ever wondered if you could one day write C# code without the need of a fully featured IDE? Well, with ScriptCS you can do just that. ScriptCS makes it possible to write C# without the need of an IDE such as Visual Studio, this is very useful if you want to do fast writes of C# without having to launch up VS each time. With ScriptCS, you can write C# in any text editor you like - including command line. And you can still use NuGet for third party libraries. Pretty cool, isn't it? You can also do things like bootstrapping external frameworks and so on. I just recently got to play around with ScriptCS, so naturally I thought to write up a tutorial on how to set up and start using this.

Chocolatey Gallery

ScriptCS is installed through the Chocolatey gallery. To install Chocolatey, start admin cmd and type the following command:

@powershell -NoProfile -ExecutionPolicy Unrestricted -Command "iex ((New-Object Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))" && SET PATH=%PATH%;%systemdrive%\chocolatey\bin

Once Chocolatey is installed, you can install ScriptCS by typing in cmd:

cinst scriptcs

That's it! To use ScriptCS, fire up cmd and simply type scriptcs. Then you can start writing C# code:

Capture

Now, let’s create something more interesting. Create a new script file called Person.csxand save it in an empty folder. You can use any text editor you like, I prefer Notepad++. Write the following C# code in your script:

class Person {

	private string _firstName;
	private string _lastName;

	public Person(string firstName, string lastName){
		_firstName = firstName;
		_lastName = lastName;
	}

	private string GetName(){
		return _firstName + " " + _lastName;
	}

	public string Greet() {
		return "Hello, " + GetName();
	}

}

Note how the object is created outside the class, and printed out to console. Now fire up cmd and execute your script by typing scriptcs Person.csx:

Capture2

Isn't this cool? Imagine the possibilities. You can now write clean C# code in script form in any text editor you like, without binding yourself to a heavy IDE. Hope you enjoyed this tutorial, and good luck!

ScriptCS-GUI

It's also worth mentioning that I stumbled upon a toolkit for ScriptCS that allows you to create GUI forms, this is quite useful when you're writing Windows applications. ScriptCS-GUI is a pretty nice framework, I recommend checking out their site here.