C#, pronounced c sharp, is a computer language used to give instructions that tell the computer what to do, how to do it, and when to do it. C# is one of the languages offered by Microsoft .NET Framework.

Console Application

Program 1: Hello World

In this lab, we will use C# language to create applications that display on a black window referred to as the DOS prompt or DOS window. These type of applications are called Console Applications. To create this type of applications we will use Visual Studio.NET 2008. Open Visual Studio.NET (VS) 2008 and on the main menu of VS environment, click File -> New Project… In Project Type choose Visual C# -> Windows. In the Templates section of the New Project dialog box, click Console Application, accept the default name or change it.
After clicking OK, a skeleton code would be created for you. Right now, we will not review every part of the code. Everything will be introduced and explained as we move on.
1. In the Main function, add this line

 Console.WriteLine("Hello World");

2. To execute the application, on the main menu, click Debug -> Start Without Debugging or Ctrl+F5
3. After viewing the result in a DOS window, press Enter to close it.

Dissecting Hello World

using System;                         // Namespace Declaration
using System.Collections.Generic;     //
using System.Linq;                    //
using System.Text;                    //
// program start class
namespace FirstLab
{
  // Main begins program execution.
  class Program
  {
    // Write to console
    static void Main()
    {
      Console.WriteLine("Hello World");
    }
  }
}
  1. The first thing you should be aware of is that C# is case-sensitive. The word “Main” is not the same as its lower case spelling, “main”. They are different identifiers.
  2. The namespace declaration, using System;, indicates that you are referencing the System namespace. Namespaces contain groups of code that can be called upon by C# programs. With the using System; declaration, you are telling your program that it can reference the code in the System namespace without pre-pending the word System to every reference (refer to point 6 for more details).
  3. The class declaration, class Program, contains the data and method definitions that your program uses to execute. A class is one of a few different types of elements your program can use to describe objects, such as structs, interfaces, delegates, and enums. This particular class has no data, but it does have one method. This method defines the behavior of this class (or what it is capable of doing).
  4. The one method within the Program class tells what this class will do when executed. The method name, Main, is reserved for the starting point of a program. Main is often called the “entry point” and if you ever receive a compiler error message saying that it can’t find the entry point, it means that you tried to compile an executable program without a Main method.
  5. A static modifier precedes the word Main, meaning that this method works in this specific class only, rather than an instance of the class. This is necessary, because when a program begins, no object instances exist.
  6. The Main method specifies its behavior with the Console.WriteLine(…) statement. Console is a class in the System namespace. WriteLine(…) is a method in the Console class. We use the “.”, dot, operator to separate subordinate program elements. Note that we could also write this statement as System.Console.WriteLine(…). This follows the pattern “namespace.class.method” as a fully qualified statement. Had we left out the using System declaration at the top of the program, it would have been mandatory for us to use the fully qualified form System.Console.WriteLine(…). This statement is what causes the string, “Hello World” to print on the console screen.
  7. Every method must have a return type. In this case it is void, which means that Main does not return a value. Every method also has a parameter list following its name with zero or more parameters between parentheses. For simplicity, we did not add parameters to Main.
  8. Observe that comments are marked with “//”. These are single line comments, meaning that they are valid until the end-of-line. If you wish to span multiple lines with a comment, begin with “/*” and end with “*/”. Everything in between is part of the comment.
  9. All statements end with a “;”, semi-colon. Classes and methods begin with “{“, left curly brace, and end with a “}”, right curly brace. Any statements within and including “{” and “}” define a block. Blocks define scope (or lifetime and visibility) of program elements.

Program 2: Adding Integers

class Calculator
{
  static void Main()
  {
    int firstNum, secondNum;
    int result;
    Console.WriteLine("Enter the first integer");
    firstNum = Convert.ToInt32(Console.ReadLine());
    Console.WriteLine("Enter the second integer");
    secondNum = Convert.ToInt32(Console.ReadLine());
    result = AddIntegers(firstNum, secondNum);
    Console.WriteLine("The result is: "+result.ToString());
    Console.ReadLine();
  }
  static int AddIntegers(int a, int b)
  {
    int c = a + b;
    return c;
  }
}

Exercise

1. Extend calculator to allow the subtraction, multiplication & division of integers.
2. Extend calculator to allow the addition, subtraction, multiplication & division of integers as well as floats & doubles.

Program 3: Arrays

In C#, an array index starts at zero. That means first item of an array will be stored at 0th position. The position of the last item on an array will total number of items – 1. In C#, arrays can be declared as fixed length or dynamic. Fixed length array can stores a predefined number of items, while size of dynamic arrays increases as you add new items to the array.

  • int [] intArray;
  • int [] intArray; intArray = new int[5];
  • int Array = new int[100];

Single-dimensional Arrays

In C# arrays are objects. That means declaring an array doesn’t create an array. After declaring an array, you need to instantiate an array by using the “new” operator.

  • int [] intArray; intArray = new int[3];
  • int [] intArray; intArray = new int[3] {0, 1, 2};
  • string[] strArray = new string[5] {“Cat”, “Dog”, “Lion”, “Elephant”, “Mouse”};
  • string[] strArray = {“Cat”, “Dog”, “Lion”, “Elephant”, “Mouse”};
  • string[] strArray = new string[]{“Cat”, “Dog”, “Lion”, “Elephant”, “Mouse”}; /*dynamic length array */

Multi-dimensional Arrays

  • int[,] numbers = new int[3, 2] { {1, 2}, {3, 4}, {5, 6} };
  • string[,] names = new string[2, 2] {{“Albert”, “Einstein”},{“Stephen”, “Hawking”} };
  • int[,] numbers = new int[,] { {1, 2}, {3, 4}, {5, 6} }; string[,] names = new string[,] {{“Albert”, “Einstein”},{“Stephen”, “Hawking”} };
  • int[,] numbers = { {1, 2}, {3, 4}, {5, 6} }; string[,] siblings = {{“Albert”, “Einstein”},{“Stephen”, “Hawking”} };

Jagged Arrays

Jagged arrays are often called array of arrays. An element of a jagged array itself is an array. For example, you can define an array of names of students of a class where a name itself can be an array of three strings – first name, middle name and last name. Another example of jagged arrays is an array of integers containing another array of integers. For example,

  • int[][] numArray = new int[][] { new int[] {1,3,5}, new int[] {2,4,6,8,10} }; Again, you can specify the size when you call the new operator.

Accessing Arrays using foreach Loop

The foreach control statement (loop) of C# is a new to C++ or other developers. This control statement is used to iterate through the elements of a collection such as an array. For example, the following code uses foreach loop to read all items of numArray.

int[] numArray = {1, 3, 5, 7, 9, 11, 13};
foreach (int num in numArray)
{
  System.Console.WriteLine(num.ToString());
}

Exercise

1. Find the largest & the smallest numbers in an array of random integers of size 10.
2. Use bubble sort to sort an array of random integers of size 10.

Array List

  • The main problem of traditional arrays is that their size is fixed by the number you specify when declaring the array variable: you cannot add items beyond the specified dimension.
  • Another limitation is that you cannot insert an item inside the list.
  • To overcome this, you can create a linked list. Instead of working from scratch, the .NET Framework provides the ArrayList class. With the ArrayList class, you can add new items to a list, insert items inside a list, arrange items of a list, check the existence of an item in a list, remove an item from the list, inquire about the list, or destroy the list. These operations are possible through various properties and methods.
  • Moreover, ArrayList can take all kinds of objects! You may add few integers, then some strings, and even some complex types including DataSet, DataTable etc. The ArrayList class is defined in the System.Collections namespace.
  • Create an ArrayList and add 4 different types of items into it…
ArrayList myList = new ArrayList();
myList.Add("Car"); // Add a string.
myList.Add(45126); // Add an integer
myList.Add(DateTime.Now); // Add current time.
myList.Add(new int[3]{0, 1, 2}); // Add a 1D integer array

Now iterate through the ArrayList and read one by one. We added 4 items of different types. So, after retrieving check the type of each item and display it.

foreach (object item in myList)
{
  if (item.GetType() == typeof(string))
  {
    Console.WriteLine("Item is a string whose value is: "
    + item.ToString());
  }
  else if (item.GetType() == typeof(int))
  {
    Console.WriteLine("Item is a integer whose value is: "
    + item.ToString());
  }
  else if (item.GetType() == typeof(DateTime))
  {
    Console.WriteLine("Item is a DateTime object whose value is: "
    + item.ToString());
  }
  else if (item.GetType() == typeof(int[]))
  {
    int[] array = (int[])item;
    Console.WriteLine("Item is an Array whose values are: "
    + array[0].ToString() + ", " + array[1].ToString()
    + " & " + array[2].ToString());
  }
}
Tagged with: C-SharpProgramming
 

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

 

Looking for something?

Use the form below to search the site:


Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Related News Feeds

Set your Twitter account name in your settings to use the TwitterBar Section.