Programming in C#, part II
Results 1 to 4 of 4

Thread: Programming in C#, part II

  1. #1
    Senior Member
    Join Date
    Feb 2002
    Posts
    170

    Programming in C#, part II

    Programming in C#, part II
    The only tutorial you need.

    Prerequisites: The tutorial "Programming in C#"

    As mentioned in part one it is my intention to write a rather large tutorial on C#. If you feel anything is missing or there is anything special you want added, don't hesitate to PM me and I'll add it. Planned TOC can be found below:

    Planned TOC so far:
    About the author.
    Getting started
    About the Microsoft.NET initiative
    What exactly is .NET
    C# and .NET - How do they relate
    Your first C#-program
    Variables. Value- and Reference types, .NET-aliases
    Reading text from the Console.
    Conditionals and Loops
    Exceptions, throwing and catching
    Namespaces, what do they do and which ones are there?
    An introduction to Windows GUI Programming
    A look at CIL, the .NET assembly language

    Actual TOC so far:
    About the author
    Getting started
    About the Microsoft.NET initiative
    What exactly is .NET
    C# and .NET - How do they relate
    Your first C#-program
    Variables. Value- and Reference types, .NET-aliases
    *** Above mentioned subjects are covered in part one. ***
    Conditionals and Loops

    Edit history:
    7/23 - Created
    7/23 - Added Conditionals and Loops

    Remeber that C# requires all code to reside inside a class. Thus, if nothing else is mentioned smaller code fragments should be put inside the Main()-metod, inside a class.

    Reading text from the console
    We have looked at how to write text to the console but a program doing no more than that might get you looked down upon by your elite C# hacking friends. It is time to catch user input. Before we do just that, we'll have a quick look at how to pass arguements to Main(). A console program many times work like a command in DOS. It is invoked from the console and passing arguments to it might often be preferable. This is done though the use of a string array, that is added added to the Main-signature like so:

    Code:
    public static void Main(string[] args)
    A program with this Main-declaration will put every space separated argument into its own element of the string array with the name args. These can later be reached with code like

    Code:
    for(int i=0; i<args.Length; i++)
    {
      Console.WriteLine("{0}",args[ i ]);
    }
    ... or something similar. Array indexes in C# are zero based so to reach the first element one would in this case write args[0] wich might be closer to reality than the loop above.

    So by using this technique we've managed to add some basic interactivity to our programs but we can't really impress anyone yet. What if we were to ask the user some questions and then store the answers in variables. In order to do this from a console program one would make use of the Read() or the ReadLine() methods of the consoe object. As one might suspect Read() reads the next charachter from the standard input stream whilst the ReadLine() method read text until it encounters a "\n" (a standard line break).

    Making use of this, we could write something like
    Code:
    Console.WriteLine("What's your name?");
    string name = Console.ReadLine();
    Console.WriteLine("Hi {0}", name);
    The data that gets pulled from the console is always of type string. This means that if you wish to store user input in an int-variable for example, thr program won't compile. In order to store input as a numeric type you can make use of the static Parse()-method that comes with most numeric types. Like so:
    Code:
    int test = int.Parse(Console.ReadLine());
    You could of course store a number in a string just as well but the number would then actually be a string and no arithmetic operations would be possible. ie "123" instead of 123.

    Conditionals and Loops
    C# supports most basic control structures found in different languages. When it comes to conditionals C# supports "if" and "else", there is however no "ifelse". The workaround for this is to put a new if-block right after the else-block.
    The conditions evaluated in C# conditionals must explicitly turn out true or false. Always. This is part of the .NET type safety.

    Code:
    int i=1
    
    if(i)
    {
     ...
    } //wont evaluate since i isn't a boolean. 1 is not equal to true
    
    if(i==1)
    {
     ...
    } // this evaluates
    If there is no more than a single line of code to execute if a condition is met, the paranthesis can be omitted. Like so:

    Code:
    if( some condition )
      //do something
    This is also why there is no real need for an ifelse-statement, The new if-statement is the only thing executing when an else is met. Like so:

    Code:
    if( some condition )
    {
      some code
    } 
    else if( other condition) //new if-block here which executes if else executes.
    {
      some code
    }
    The other conditional structure supported by C# is the switch case. Switch case structures are convienient if you know beforehand what kind of values a certain variable might contain. Very important to note in C# is that switch cases aren't allowed to fall through. This means that a break-statement must end every case. This is an example:

    Code:
    switch(myVar)
    {
      case 1: // if myVar is one...
        do something ...
        break;
    
      case 2: // if myVar is two ...
        do something else ...
        break;
    
      default:
        /*if myVar is something unexpected ...
          .... no need for a 'break here'  */
    }
    So far we've looked at conditionals or the ability to programmatically branch a program based on certain boolean evaluations.
    If a certain block of code needs to be repeated for a number of iterations or until a certain expression evaluates to something we need to make use of looping. C3 supports three different loopeing techniques; for; while and do while. We've seen the for-loop before and syntactically it looks just like a for-loop in C, C++, JScript or Java.

    Code:
    for(int i=0; i<100;i++)
    {
      Console.WriteLine("This is line {0}", i.ToString());
    }
    The code above will iterate from 0 'till i is less then 100, ie 99. Each line the program will write "This is line 0", "This is line 1" and so on.
    The for-loop is very useful when you want to loop trough an array, a collection or something similar. Above, I've showed how to loop through an array with "for(int i=0; i<args.Length; i++)" where args is the array of unknown size.
    Sometimes one might want to loop something while a certain expression evaluates to a certain value. At times like these the while-loop comes in handy. Again, the syntax is exactly the same as in C++ or Java:

    Code:
    while(myVar < 100)
    {
      Console.WriteLine("myVar is now {0}", myVar);
      myVar++;
    }
    If you want the block executed at least one time (and suprisingly often, this is exactly what you want to achive) it is possible to move the while statement to after the block to create something similar to the Visual Basic Do...While-expression. Like so:

    Code:
    {
      Console.WriteLine("myVar is now {0}", myVar);
      myVar++;
    }
    while(myVar < 100)
    These are the fundamental logical building blocks of C#. With these control structures it is possible to pretty much create any sort of script logic.

    A suggested exercise at this point is to write a program that based on user input, makes use of a conditional statement as well as a loop of your choise.
    Mankan

    \"The purpose of abstraction is not to be vague, but to create a new semantic level in which one can be absolutely precise.\"
    - Edsger Dijkstra

  2. #2
    Senior Member
    Join Date
    Nov 2001
    Posts
    4,786
    let me be the fist to say thank again. the sdk is downloading now and as soon as its finished ill be following you. just want to give you positive feed back so you keep writing ;-)
    Bukhari:V3B48N826 “The Prophet said, ‘Isn’t the witness of a woman equal to half of that of a man?’ The women said, ‘Yes.’ He said, ‘This is because of the deficiency of a woman’s mind.’”

  3. #3
    Well said, Tedob1, I was wondering what MS was using for ASM now. CIL sounds interesting, and I really hope to see that, and look forward to great things from you

    //applauds Mankan

  4. #4
    Senior Member
    Join Date
    Feb 2002
    Posts
    170
    There is an error in the do... while loop above. There is a semi-colon missing but if it is added the block will execute once and then go into an infinite loop. Below is the correct code.

    Code:
    do{
      Console.WriteLine("myVar is now {0}", myVar);
      myVar++;
    }
    while(myVar < 100);
    Sorry 'bout that.
    Mankan

    \"The purpose of abstraction is not to be vague, but to create a new semantic level in which one can be absolutely precise.\"
    - Edsger Dijkstra

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •