The Basics: Your First Program
In this beginner’s series, I will be taking you through the various parts of a common C# program. These tutorials will help build the foundation for more advanced ones later. In the first installment, we will be taking a look at a very, very basic example and going over what each line of code means.
Overview
The “Hello World” is a traditional first program and has been done in every programing language known. C# is no exception to this.
Code
using System;
class HelloWorld
{
static void Main(String[] args)
{
Console.WriteLine("Hello, World!");
}
}
Analyis
Let’s take a look at the first line of code:
using System;
In C#, by placing a using statement in the header portion of the source code you are linking to existing code. In this case you are linking to the basic .NET libraries that you need to use certain functionality later on in the program. The technical term for a word like “System” that points to a reference is “namespace”. System is the top level namespace for the .NET standard library. We’ll cover namespaces more in depth later, but for now just know that every program you write in C# will use at the very least System.
class HelloWorld
A class is a logical container for code that’s involved in object orientated programming. Basically a class provides the blueprint for creating highly reusable code. In C#, all code must be included in a class – even the simplest of programs that don’t utilize the OOP model. You will be dealing heavily with classes and objects later, but for now know that the “class” keyword defines a logical block of code.
Notice the curly brackets or braces. These are used to define “scope” within your program. In our example program, everything within the first set of braces belongs to the HelloWorld class definition. They are used again in the next section.
static void Main(String[] args)
Here we have our entry point in the program: our “Main” method. A method is part of your program that does something. You could have a method named “add()” which could add two numbers together or “sortAlphabetically()” or whatever. The idea is that a method performs a standard action and can return a result.
All programs must contain a Main method which is the method that is called first when a program is run. In our example we declare the Main method to be “static”, which means that the method does not require an instance of the class to run (another OOP topic). We also must declare what the method will return or its “return type”. In this case we are returning nothing, therefore we say that it’s “void”.
Our next bit of code “String[] args” declares what can be passed into the method. In this case we are passing an array of Strings which we store in the variable name “args” which is sort for “arguments”. This is called the method’s parameters. String[] args in a Main() method allows us to pass parameters directly into the program from the command line. If we compiled this into an executable named hello.exe, we could type:
C:\hello.exe hello
And our program would be run, passing in “hello” to the Main() method. We don’t use the arguments in our example, but it’s good practice to put them there anyway.
The declaration line of a method is referred to as the method signature.
Console.WriteLine("Hello, World!");
Finally we come to the meat of our program. Here we calling a method named “WriteLine” from the Console class under System. This line would work just as well as if we wrote it:
System.Console.WriteLine("Hello, World!");
Since we declare that we are using “System” in the header, we can use the short form of “Console.WriteLine” instead.
Console is part of the core .NET functionality regarding input and output on the command line or “console”. This method will print a string passed into the method to the screen and follow it with a return or “newline character”. Console.Write will do the same thing, but not include the return.
Notice that the string “Hello, World!” is wrapped in quotation marks. This indicates that it is a raw string and not the name of a variable or a number (ie 1234, 44.54, etc) which do not require the quotation marks.
Compiling
To compile a C# program you can either use Visual Studio or the command line compiler named “csc.exe”. To compile, simply:
csc.exe nameofsourcefile.cs
A big “gotcha” is that csc is not normally in your default path. You can add this in environment settings, or use the Visual Studio command prompt which includes it in its path by default.
If all goes well and you get no errors, you will have an exe file named the same as your source code file which you can run from the command prompt.
Conclusion
This has been a very high level overview of the basic parts of a command line program written in C#. The intent is to get you used to the layout and basic flow of a program. By being able to recognize the scope as laid out by braces and knowing how to identify a method, you will have the basics of reading a program down.
Understanding Interfaces
A coworker and I got into a conversation today about interfaces versus abstract classes. I came up with a pretty good analogy for him, and thought it would be a good blog post.
Overview
An interface class is an extremely useful tool for abstraction in C#. Unfortunately, many developers either don’t understand how they should be used or what makes them distinct from abstract classes.
Simply put: an interface represents a verb while an abstract class represents a noun.
Take for example the standard interface IEnumerable. Classes such as List implement IEnumerable which defines certain things that a List must do like move to the next record or get the current record. If you wanted to make your own collection class, you could implement IEnumerable and use such niceties as a foreach loop to iterate through it. An interface is a series of method names and signatures with no implementation. All of these methods must be implemented by any class that implements it.
Contrast this with an abstract class which does not require classes that inherit from it to do anything. It simply provides the framework of the class; it abstracts the commonality of several classes into one to describe classes that inherit from it. Abstract classes can contain methods that are implemented, and classes that inherit from the abstract class do not necessarily have to implement its methods.
Example
The essence of an interface is that it guarantees that a given class that implements it will be able to do certain standard things. My favorite example is of a group of classes that deals with vehicles:
- Vehicle (abstract)
- IHonkable (interface)
- Bus (concrete)
- Tank (concrete)
In our abstract Vehicle class we have certain common things that all vehicles do like drive() or turn(). In our IHonkable interface we have certain things that only some vehicles do such as honk(). Obviously since a Tank can’t honk, it wouldn’t implement IHonkable but Bus would.
To take this example a bit further, let’s add another class: Car. Obviously a car has a horn that can honk, so it would implement IHonkable. However, since the mechanism in a car horn may be different from that in a bus, it’s implementation is different. However, a driver that is familiar with honking a horn in a car, can easily do so in a bus because they share a common interface.
The Microsoft standard for naming interfaces says we should prefix them with “I” followed by some potential verb. IHonkable, ISortable, IEraseable would all be good examples of interface names.
Remember that any class that implements your interface will need to be updated if any changes are made to the interface. Changing an interface is always potentially code breaking. It’s good practice to make an interface as specific as possible, containing just enough methods to get the job done. Sometimes it’s better to use an abstract class, and with experience you’ll be able to know when to use either. You inherit an abstract class but you implement an interface. Remembering this terminology can help in remembering how and when to use an interface or an abstract class.
Code
Here’s an example of a basic interface class definition:
public interface IHonkable
{
int decibelLevel
{
get;
set;
}
void honkHorn(Decimal duration);
}
And here’s an example of a class that implements IHonkable:
public class Bus : IHonkable, Vehicle
{
public Bus
{
decibelLevel = 81.0;
}
void honkHorn(Decimal duration)
{
Horn myHorn = new Horn();
myHorn.honk(decibelLevel,duration);
}
}
Welcome to C Sharpener
Hello all, I’m James and I’ll be your guide. This blog’s aim is to play host to some of the best tutorials on the C# language as well as my musings on software development. If you’re a newbie learning C# for the first time or are completely new to programming you’ll find something here.
Thanks for stopping by.