Your First C# Program C# Help

Let’s start by compiling and running the simplest possible C# program – a simple class consisting of a console application that writes a message to the screen.

The most common technique for writing C# programs is to use Visual Studio 2008 to generate a basic project and add your own code to it. However, because the aim of these early chapters is to teach the C# language, we are going to keep things simple and avoid relying on Visual Studio 2008 . Instead, we will present the code as simple files that you can type in using any text editor and compile from the command line.

The Code

Type the following into a text editor (such as Notepad), and save it with a . es extension (for example, First. c s). The Main () method is shown here:

.using System:
namespace Wrox.ProCSharp.Basics
class MyFirstCSharpClass
static void,Main()
Console.WriteLine(‘This isn’t at all like Java!’);
Console.ReadLine() ;
. }



Compiling and Running the Program

You can compile this program by simp’y running the C# command-line compiler (ese. exe) against source file, like this:

           csc First.cs

If you want to compile code from the command line using the ese command, you should be aware the .NET command-line tools, including ese, are available only if certain environment variables have been set up. Depending on how you installed .NET (and Visual Studio 2008), is may ‘or may not be case on your machine.

If you do not Iun1t tM envinmmmt “f1flriQblesset up, you Iun1t the following two options. The first is to run the batshfiie ‘Microsoft Visual Studio 2008\\COII’IIIon7\Tools\vsvars32 .bat from the command prompt btforr running csc, whert ‘Microsoft Visual Studio 2008 is thefolder to which VisUQ/Studio 2008 hils bten installed. The second, and easier, way is to use the VISual Studio 2008 command prompt ill.~ if the usual command prompt window. You willfind the VJSUQ/Studio 2008 command prompt in the Start Menu, under Programs, Microsoft VISUIlIStudio 2008, Microsoft VISual Studio Tools. It is simply a command prompt window that automatically runs vsvars 32 .ba t when it opms.

Compiling the code produces an executable file named First. exe, which you can run from the command line or from Windows Explorer like any other executable. Give it a try:

csc First.cs

Microsoft (R) Visual C. Compiler version 9.00.20404
for Microsoft (R) .NET Framework version 3.5
Copyright (C) Microsoft Corporation. All rights reserved.


This isn’t at all like Java.

Well, maybe that message isn’t quite true! This program has some fairly fundamental similarities to Java, although there are one or two points (such as the capitalized Main () function) to catch the unwary Java or C++ developer. Let’s look more closely at what’s going on in the code.

Posted on October 27, 2015 in C# Basics

Share the Story

Back to Top
Share This