Simple environments for quickly testing .NET functionality

0

Full article

This post was inspired by a question on SO. It was a simple question about what the integer data type in C# does with the decimal portion of a number. The question itself is not the point, as much as the fact that it could have easily been avoided altogether by running the code and comparing the results. The astounding part was this statement:

I have to know before I run the code, cause it will jack everything up if it is wrong. I don’t mock a test environment. I simply don’t have enough knowledge on how to set one up.
Livin' dangerously...

Testing code doesn’t have to require an elaborate setup. Here's a couple simple ways to try out some .NET functionality.

Create a .NET Fiddle

If you’ve just got a short snippet to try out, consider using .NET Fiddle, which allows you to setup an empty Console app and run code (C#, F# or VB.NET) online. It even accepts user input via Console.ReadLine(), which makes it that much more useful.

dotnetfiddlesample

There are similarly styled sites for other languages too, such as SQL Fiddle and JS Fiddle(for JavaScript). The drawback is that you can’t debug your code by setting a break point and stepping through it line by line, but the benefit is that you can share the code snippet and even embed it in your site.

Setup a Console Application

The next fastest way to test something (IMO) is to setup a simple Console Application. It’s got minimum overhead, and you can place break points and step through the code.

newconsoleapp1
newconsoleapp2

When you create the application, you’ll have one code file (program.cs), with the following contents.

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
        }
    }
}

Insert a Console.ReadLine() statement, and keep it as the last line, so the console window stays open while you check out the results (if any) of whatever code you’re executing.

static void Main(string[] args)
{
    Console.WriteLine(DateTime.Now);
    Console.WriteLine();

    Console.WriteLine("Today's date is: {0:g}", DateTime.Now);
    Console.WriteLine();

    Console.WriteLine("Press any key to exit.");
    Console.ReadLine();
}
consolesample

Beyond...

If you want to see the effects of code on any GUI component, you’ll have to setup the appropriate project type, but these two approaches will allow you to quickly test a great deal of .NET functionality in such a way that you won't "jack everything up if it is wrong". 😅

Author

Grant Winney

Is there anything more satisfying than sharing knowledge? Of teaching someone and witnessing their "ah ha" moment? I usually write about tech, but no promises. I hope you find something interesting!



Comments