Advertisment

Programming in C#

author-image
PCQ Bureau
New Update

C# is one of the premier weapons in the .Net armory and is much talked about these days. Over the past few months, we’ve carried articles where we’ve used code written in C#. Starting this month, we’ll show you how to program in C#. The articles will be written from a beginner’s point of view, though there are few assumptions we’ll make. These are that you’re familiar with object oriented programming (OOP) and terms like classes, objects, method, virtual functions, et al; and that you do have some programming experience, preferably in a language like C, C++, or Java (please refer to the article on object oriented programming, titled OOPS Explained, page 169, in this issue if you need to familiarize yourself with these concepts).

Advertisment

To work on the code that will be provided, you should have the .Net SDK Beta 1 or the Visual Studio.NET installed on your system. The .Net SDK is provided in the accompanying CD. Please note that this is an early beta and you should not install it on a production machine. By the time you read this, Beta 2 may be out. If that is the case, we’ll provide you with Beta 2 of the .Net SDK on next month’s CD. 

Hello World

Let’s not start by breaking traditions. So, we’ll get going with the Hello World! C# program:

Advertisment

// This is my first C# program

using System;

class CHelloWorld

{

public static void Main()

{

Console.WriteLine(“Hello World!”);

}

}

This will seem familiar to C/C++/Java guys. Let’s dissect it to understand C# further.

To begin with, remarks are identified using the familiar C/C++ style–two forward slashes, //. You can also use the standard C /* */ remark indicators if you have multiline remarks coming up in your code. 

Advertisment

Now we come to unfamiliar territory–using System;. To understand what this does, go back to the #include preprocessor directives which you use in C/C++. While the #include directive helps declare the prototypes of the functions to be used in the program along with any other class, structure, or union declarations; the using keyword in C# defines the namespace to be used by the program. Simply put, a namespace is a collection of classes grouped together, usually on the basis of the functionality they provide. So, when the program says

using System;

what this really means is that the program is going to use classes defined in the System namespace. The System namespace happens to be the most used and useful, general-purpose .Net namespace, providing facilities like working with strings, integers, arrays, and more. Java programmers will find the functionality of the using keyword similar to that of the import keyword.

Advertisment

Moving on, we come to the line where the CHelloWorld class has been defined. This is another change from traditional C/C++ programming. While you can have functions outside a class in C/C++, in C#, like in Java, all functions are members of some class or the other. And any one of the classes should define and implement the Main method, which serves the same purpose as main in C/C++, to start program execution. However, there is a difference–C#’s Main has a capital M instead of the lowercase m in C/C++.

We now come to the signature of the Main method.

public static void Main()

Advertisment

Parsing from right to left, we first encounter void, the meaning of which is that the Main method isn’t going to return any value to its caller–the .Net runtime environment. Values are usually returned from the Main method to return error codes, if any, to the operating system or runtime environment. Next, we have the static keyword. This holds the same meaning as it holds under C++ and Java. So, if you are familiar with it, you can skip the following discussion. 

OOP helps us design software to tackle real-life problems better by introducing the concept of user-defined data types, which help abstract real-life objects as closely as possible. These user-defined data types are termed as classes. To use a class, you have to instantiate it. That is, you have to declare a variable whose type is the user-defined data type (the class). So, if ChelloWorld is a class, then it is instantiated as:

CHelloWorld, obj;

Advertisment

where obj is a variable of the type CHelloWorld class. Technically, obj is said to be an object of the class
CHelloWorld. 

Now, within the class declaration, we declare the functions and variables that define the functionality and characteristics of the class respectively. In OOP terminology, these functions are called methods and the variables are called properties. Traditionally, methods and properties are used upon the instantiated object, and not the whole class. That is, if size happens to be the property of the ChelloWorld class, and obj is an object of the type CHelloWorld¸ then size would referred to as:

obj.size=10;

Advertisment

if it were being assigned a value. In the same manner, the methods are called upon the object variables. Hence, for two different objects, the size property could be carrying different values. Hence, properties and methods are usually worked upon a per-object basis.

However, there are times when properties or methods need to be worked upon a per-class basis. In such a case, they’re prefixed by the static keyword, which tells the compiler that the property or method should be made existent on a per-class basis, and not on per-object basis. And that’s what the Main method of the class CHelloWorld is. It’s a per-class method, and the calling convention of static methods is:

CHelloWorld.Main

The structure is: .

Finally, we get to the public portion of the method signature. In OOP, we can define what methods and properties are accessible to what portions of the program. The public keyword specifies that the method is accessible to all parts of the program which can successfully instantiate the class containing the method.

Now we come to the crux of the program, which displays Hello World! on the screen:

Console.WriteLine(“Hello World!\n”);

WriteLine is a static method of the Console class in the System namespace and hence, is written using the . format. 

In the implementation shown here, WriteLine works functionally identical to printf of C or cout in C++. There are many implementations of the WriteLine method, which take various kinds of input parameters. That is, Console.WriteLine is overloaded in OOP terminology. Moving on, we close the braces of the Main method, followed by the closing of the braces of the class
CHelloWorld. 

Before I end this discussion, one important point regarding the return value of the Main method. It can only return void, that is, return nothing to the caller; or int, that is, return an integer value, and nothing else. Well, so much for the dissection of this simple-looking program, which simply displays a string. Now, let’s do some I/O with the user.

Working with input

Parallel to Console.WriteLine is the static method of the Console class, which reads in a line of string from the user. Here’s a simple program to illustrate this:

// This is my second C# program

// and it takes an input from the user

using System;

class CHelloWorld

public static void Main()

{

Console.WriteLine(“Enter your name: ”);

string strName=Console.ReadLine();

Console.WriteLine(“Hello “ + strName);

}

}

The new thing here is that we use the Console.ReadLine method to read in a string of characters and store it in the variable strName, which is of the type string. string is a built-in .Net data type for working with strings and other character data. The ReadLine method continues to read in characters until a carriage return is encountered, after which it stores the read characters in the applicable variable. Once the user enters his name, which is then stored in the strName variable, we display it using the second Console.WriteLine. The ‘+’ operator concatenates the contents of the strName variable with the portion within double quotes and displays it. So, if I were to enter ‘Gaurav’ when prompted, it would display Hello
Gaurav. 

In the above example of user input, we directly concatenated the variable contents to the string. However, that’s not the only way to do it. Here’s another version of the same program:

// This is my second C# program

// and it takes an input from the user 

// and displays it using markers

using System;

class CHelloWorld

{

public static void Main()

{

Console.WriteLine(“Enter your name: ”);

string strName=Console.ReadLine();

Console.WriteLine(“Hello {0}“ ,strName);

}

}

The only change observed here is in the second Console.WriteLine, which now uses a formatted string implementation. Within the formatted string, we can have markers like {0}, {1}, and so on. What they mean is that {0} shall be replaced by the contents of the first variable in the variable list, {1} will be replaced by the contents of the second variable in the variable list and so on. Here’s another example.

using System;

class CHelloWorld

{

public static void Main()

{

Console.WriteLine(“Enter your name: ”);

string strName=Console.ReadLine();

Console.WriteLine(“Enter your city: ”);

string strCity=Console.ReadLine();

Console.WriteLine(“From {1}, I welcome {0}“ ,strName, strCity);

}

}

In this case, if I were to enter my name as Gaurav and my city as Chandigarh, then the output will be:

From Chandigarh I welcome Gaurav

Markers are zero based, so {0} refers to the first variable, {1} refers to the second and so on. WriteLine can support upto three such markers, that is, till {2}.

Each of the programs used above are fully functional and can be compiled. To do so, save them to a file, with extension CS (for C#), and compile from the command line as follows.

C:\>csc

csc is your command line C# compiler, available if you have .Net SDK Beta 1 or Visual Studio.NET installed. The command, upon execution, will produce an executable file with the same name as the source, and in case you notice, there aren’t any intermediate object files being produced.

We hope that this introduction to C# has helped you start smoothly with this new development
environment, and that you enjoyed it as much as we did.

Kumar Gaurav Khanna

Advertisment

Stay connected with us through our social media channels for the latest updates and news!

Follow us: