C#

The whole new way of programming�

Oh no! Not another language! That is likely to be the initial reaction of most developers towards C#. But if they scratch the surface a bit then they would appreciate the treasures that it holds. Rather than extending the languages to meet today�s technological challenges C# has been built from ground up to meet these challenges with no overheads of backward compatibility.

If you are a C++ or a Java programmer you would find lot of things similar when you take a first look at C# code. However, apart from the initial similarity you will find C# a lot easier than C++ and Java. It offers simplicity of Visual Basic, power of C++ and platform independence of Java, all bundled into one language. The highlighting features of C# are as follows:

  1. Full support for object-oriented programming
  2. In-built support for automatic generation of XML documentation.
  3. Automatic cleanup of dynamically created memory.
  4. Access to .Net class library as well as Windows API.
  5. Can be used to create a ASP.Net dynamic web pages.

Most of these features are available on VB.Net as well as VC++.Net. However, since C# is designed from the start to work with .Net, it uses .Net features with ease and efficiency that would be found wanting in VB.Net and VC++.Net.

C# has been developed by a team led by Anders Hejlsberg who was also the leader of the J++ team. Hence you will find the design and syntax of C# much similar to Java. However, as of now Java has one strong advantage over C#�platform independence. The same Java code can be executed on any platform that has a Java Runtime (JVM) implementation. Since JVM�s are already in existence for most major platforms Java is truly portable today. Same is not true about C#�at least not as of now. In contrast, C# has two advantages over Java. These are as under:

  1. C# supports operator overloading. If required C# programs can use pointers by enclosing them within �unsafe� blocks.
  2. C# can interoperate with code written in other .Net languages.

Without much ado lets get on with C# programming. Here we go�

The First C# Program

All that you need to program in C# is Microsoft VisualStudio.Net Beta 2, .Net SDK Beta 2. (These you can either download from msdn.microsoft.com or you can get it along with your MSDN subscription.) You need to install it on a machine running under Windows 98, Windows 2000 or Windows XP.

namespace Simple

{

using System ;

class Class1

{

static void Main ( string[ ] args )

{

Console.WriteLine ( “Hello C#” ) ;

}

}

}

Before we understand how the program works, let us first see the steps involved in creating it.

Steps involved:

  1. Start Microsoft Visual Studio.NET 7.0 from Start | Program | Microsoft Visual Studio.NET 7.0 menu option.
  2. Create a new C# project from File | New | Project menu option. A New Project dialog as shown in the following figure would appear.
  3. From the New Project dialog box select project type as Visual C# Projects.
  4. Select Console Application from the list of Templates.
  5. Select a location (directory/folder) where this project should get saved. Give name to the project as Simple. Click on OK button.
  6. A Class1.cs file would get created. This file would contain skeleton program. The VisualStudio.Net environment automatically creates this program. It contains a class called Class1 containing the function Main( ) .
  7. Add the following line to the skeleton code.
  8. Console.WriteLine ( “Hello C#” ) ;

  9. To compile and execute the program use Ctrl + F5. On execution the message “Hello C#” would be displayed on the screen.
  10. Now a few useful tips about the program�

  11. C# is a pure object oriented language. It doesn�t allow global variables or functions. All variables and functions should be defined inside a class.
  12. All C# programs start from Main( ). Since Main( ) cannot be global it is enclosed in a class called Class1. void before the word Main specifies that Main( ) does not return anything. The static modifier used with Main( ) indicates that it can be called without creating an object of the class Class1.
  13. string is a data type used to store strings. string[ ] represents an array of strings. Thus args is an array of strings. It stores the command line parameters, if specified by the user while executing the program.
  14. To display anything on the screen we need to call the WriteLine( ) function. To this function we can pass strings, integers, floats, etc. Since the WriteLine( ) function belongs to the Console class we have to call it using Console.WriteLine( ). A function within the class can be accessed using the �.� Operator. Console class is used to perform input from keyboard and output to screen.
  15. In C#, namespaces provide a way to group classes. Console class belongs to the System namespace. Hence to be able to use the Console class we need to import it from the System namespace. This has been done through the using System statement. The way the Console class has been enclosed within the System namespace, likewise our class Class1 has been enclosed in the Simple namespace. The namespace concept is similar to packages in Java.
  16. C# is a case-sensitive language. The naming convention used by .NET is that class names would start with a capital letter. If a single class name contains multiple words, each word’s starting letter would be capital. The same applies to function names also. All keywords are in small case.

Let us now write another program that would show how to receive input from the keyboard. Here it is�

namespace Simple

{

using System ;

class Class1

{

static void Main ( string[ ] args )

{

string s ;

s = Console.ReadLine( ) ;

Console.WriteLine ( s ) ;

}

}

}

To receive input from the keyboard we have used the ReadLine( ) function. This function returns a string. This function is also a static member function of the Console class, hence we have called it using Console.ReadLine( ).

Note that C# does not have its own class library. It uses the class library provided by the .Net Framework. The .Net Framework provides the class library in the form of .Net Base Classes. Thus Console is a .Net base class. This class can be used by any other .Net-aware language.

Command-line Arguments

Instead of receiving input from keyboard we may want to supply input to it in the form of command-line arguments. Following program shows how to receive these arguments and print them out.

using System;

namespace cmdline

{

class Class1

{

static void Main ( string[ ] args )

{

foreach ( string str in args )

{

Console.WriteLine ( str ) ;

}

}

}

}

To supply command-line arguments we have to open the properties window of the project from the “Solution Explorer”. A window will pop up. This window consists of properties that appear on the left pane of the window. We have to select “Configuration Properties” from it. As soon as we select this it expands into a tree with more underlying properties. Now we have to select the “Debugging” property. On doing this all fields related to the “Debugging” property appear on the right pane of the window. We then need to fill in the command-line arguments in the “Command Line Arguments” option. Press OK to finalize the option. In this program we have set command-line arguments as Nagpur Mumbai Bangalore. On executing the program it would output these arguments.

We can run this program from the Run dialog box that appears when we select �Start | Run� option. To do so we must specify the command line arguments after the name of the EXE file.

FileHandling

.Net offers two classes for file operations�the File class and the FileInfo class. Both these classes are defined in System.IO namespace. The File class is derived from the Object class. It contains static methods and never gets instantiated. The FileInfo class is derived from FileSystemInfo class, which represents the file system. We can instantiate this class. The hierarchy of these classes is shown in the following figure:

Let us now understand the objective of creating two classes for file operations.

The static functions of the File class can be called to perform various file operations without creating an object. This avoids the overhead of instantiating objects. As against this, to call the member functions of the FileInfo class it is necessary to create an object. This is because FileInfo class contains non-static member functions. So if we wish to carry out a single operation on the file we can use the File class, avoiding the object creation overheads thereby. On the other hand if we wish to carry out multiple operations on the file (with the preservation of state of the object) we can use the FileInfo class. When we create a FileInfo object all the relevant information like size, attributes, authentication permissions are read in through the constructor. This information is then shared by other functions while carrying out multiple operations. If we use the File class for carrying our multiple operations then this information will have to be read in each time we perform a new operation.

Also, at times we are required to pass the file information to another application. In such a case it is necessary to create a FileInfo object and then pass its state to other application (this process is known as marshalling). Marshalling of object is possible only if the class in derived from the MarshalByRefObject class. Since the object of the File class cannot be created it has not been inherited from MarshalByRefObject class.

Reading And Writing To A Text File

In the following program we will perform reading and writing operations on a text file. We plan to write a few strings to a text file and read the strings back from it.

namespace fileoperation

{

using System ;

using System.IO ;

class Class1

{

static void Main ( string[ ] args)

{

string str1 = “The .NET Revolution” ;

string str2 = “Long live C# ” ;

string str3 = “Targeting the internet” ;

StreamWriter sw =

new StreamWriter ( “C:\\file2.txt”, false ) ;

sw.WriteLine ( str1 ) ;

sw.WriteLine ( str2 ) ;

sw.WriteLine ( str3 ) ;

sw.Close( ) ;

StreamReader sr =

new StreamReader ( @”C:\file2.txt” ) ;

// @ ensures that we don’t have to use C:\\

string str ;

do

{

str = sr.ReadLine( ) ;

Console.WriteLine( str ) ;

} while ( str != null ) ;

sr.Close( ) ;

}

}

}

To understand this program we must first know what a Stream is. A stream is a sequence of bytes traveling from source to destination or traveling over a communication link. Two basic types of streams exist: Input stream and Output stream. An input stream is used for read operations while an output stream is used for write operations. The System.IO namespace contains functions to perform input and output operations.

Here we have created a new StreamWriter object and have passed �false� to the constructor of the StreamWriter class along with the path. Here ‘false’ specifies that if the file exists, it should be overwritten. If we pass a true and if the file exists, it should be appended. In either case if the file does not exist, a new file is created. The WriteLine( ) member function of the StreamWriter class is overloaded to write out entities like object, boolean, int, etc. to a file.

Next, we have used a StreamReader class to perform the reading operation. Its ReadLine( ) function reads a line of characters from the current stream and returns the data as a string. This process is repeated till the end of file is reached. The hierarchy of stream I/O classes is shown in the following figure:

We have taken the first few toddling steps in C#. Imbibe the matter presented here. We would take a peek below the hood of C# and explore its internal working next time.

It's very calm over here, why not leave a comment?

Leave a Reply




Feed Feed
Feed Feed