September 8, 2024

A proper C# Program

No top level statements here. We have all the "ceremony" and this will work with ancient versions of C#, almost certainly including Mono.
using System;

namespace HogHeaven
{
    public class Program
    {
        public static void Main(string[] args)
        {
            Console.WriteLine ( "Kilroy was here." );
        }
    }
}

// THE END
Here you see one of my conventions. I always put a "THE END" comment at the end of every file. In the first "first" program, the compiler was providing all of the ceremony and hiding it from you.

You can learn as much by just looking at this as me telling you about it, but here we go anyway. The first "using" line says that we intend to use stuff from the "System" namespace (namely the Console.WriteLine() method). In proper and wholesome C#, everything needs to be in a namespace, and "HogHeaven" seemed like just the right thing to me. Next the Main() method needs to belong to some class. We could invent yet another crazy name, but "Program" does serve to make our intent clear, so we go with that. Main could get (and process) an array of strings (command line arguments), so we have that even though they are never used.

If you don't understand the basics of classes, methods, and object oriented programming, you will need to go elsewhere. I don't intend to go into that here and there are a myriad of sources. I may make "interesting" comments when something unique about classes and OO catches my eye.

Let me talk about the word "static". What this means is that we don't need to create an instance of the Program class to use the Main() method. Every OO language has its own set of jargon for these things. In Ruby this would be called a "class method" which I think makes sense. But this is C# so we call it a static method, overloading the word "static" that is used for several things in C family languages.


Feedback? Questions? Drop me a line!

Tom's Computer Info / tom@mmto.org