C# Basic (7)

1. The application requests that the user type in a number between 1 and 10. A random number is then generated, and the user is told whether the number they picked matches the random number.

using System;

class IfTest1App
{
    const int MAX = 10;

    public static void Main()
    {
        Console.Write("Guess a number between 1 and {0}...", MAX);
        string inputString = Console.ReadLine();

        int userGuess = inputString.ToInt32();

        Random rnd = new Random();
        double correctNumber = rnd.NextDouble() * MAX;
        correctNumber = Math.Round(correctNumber);

        Console.Write("The correct number was {0} and you guessed {1}...",
                       correctNumber, userGuess);
        if (userGuess == correctNumber) // They got it right!
        {
            Console.WriteLine("Congratulations!");
        }
        else // Wrong answer!
        {
            Console.WriteLine("Maybe next time!");
        }
    }
}

ask the user which language he or she is currently using

using System;

class IfTest2App
{
    const string CPlusPlus = "C++";
    const string VisualBasic = "Visual Basic";
    const string Java = "Java";

    public static void Main()
    {
        Console.Write("What is your current language of choice " +
                       "(excluding C#)?");
        string inputString = Console.ReadLine();

        if (0 == String.Compare(inputString, CPlusPlus, true))
        {
            Console.WriteLine("\nYou'll have no problem picking " +
                                 "up C# !");
        }
        else if (0 == String.Compare(inputString, VisualBasic, true))
        {
            Console.WriteLine("\nYou'll find lots of cool VB features " +
                                 "in C# !");
        }
        else if (0 == String.Compare(inputString, Java, true))
        {
            Console.WriteLine("\nYou'll have an easier time " +
                                 "picking up C# <G> !!");
        }
        else
        {
            Console.WriteLine("\nSorry - doesn't compute.");
        }
    }
}

The expression evaluated must result in a Boolean value. While in C++ where you’re allowed to use the if statement to test for any variable having a value other than 0.

2.   Switch like C++,  need Break; to stop the case, else if you want combining case labels.

using System;

enum Tenders : int
{
    Cash = 1,
    Visa,
    MasterCard,
    AmericanExpress
};

class Payment
{
    public Payment(Tenders tender)
    {
        this.Tender = tender;
    }

    protected Tenders tender;
    public Tenders Tender
    {
        get
        {
            return this.tender;
        }
        set
        {
            this.tender = value;
        }
    }

    public void ProcessPayment()
    {
        switch ((int)(this.tender))
        {
            case (int)Tenders.Cash:
                Console.WriteLine
                           ("\nCash - Everyone's favorite tender.");
                break;

            case (int)Tenders.Visa:
            case (int)Tenders.MasterCard:
            case (int)Tenders.AmericanExpress:
                Console.WriteLine
("\nDisplay Credit Card Authorization Dialog.");
                break;

            default:
                Console.WriteLine("\nSorry - Invalid tender.");
                break;
        }
    }
}

class CombiningCaseLabelsApp
{

    public static void Main()
    {
        Payment payment = new Payment(Tenders.MasterCard);
        payment.ProcessPayment();
    }
}

3. Using the foreach statement, you can iterate through any collection or array in a uniform manner.

using System;
using System.Collections;

class MyArray
{
    public ArrayList words;

    public MyArray()
    {
        words = new ArrayList();
        words.Add("foo");
        words.Add("bar");
        words.Add("baz");
    }
}

class Foreach2App
{
    public static void Main()
    {
        MyArray myArray = new MyArray();

        foreach (string word in myArray.words)
        {
            Console.WriteLine("{0}", word);
        }
    }
}

P.S.  while(true) = for(;;)

4. Jump statements: break, continue, goto, and return.

goto statement can take any of the following forms:

goto identifier
goto case constant-expression
goto default

Using the return statement with exception handling:  If the return statement is a try block that contains an associated finally block, control is actually passed to the first line of the finally block, and when that block of code finishes, control is passed back to the caller. If the try block is nested in another try block, control will continue back up the chain in this fashion until the final finally block has executed.

 

5. Error Handling

If an exception is thrown and no catch block is found in the current call stack, the application will abort.

using System;

public class ThrowException1App
{
    public static void ThrowException()
    {
        throw new Exception();
    }

    public static void Main()
    {
        try
        {
            Console.WriteLine("try...");
        }
        catch(Exception e)
        {
            Console.WriteLine("catch...");
        }
        finally
        {
            Console.WriteLine("finally");
        }
    }
}

An useful property of the System.Exception class is the StackTrace property. The StackTrace property enables you to determine what the current call stack looks like.

using System;

class StackTraceTestApp
{
    public void Open(String fileName)
    {
        Lock(fileName);
        // ...
    }
    public void Lock(String fileName)

    {
        // Error condition raised.
        throw new Exception("failed to lock file");
    }
    public static void Main()
    {
        StackTraceTestApp test = new StackTraceTestApp();

        try
        {
            test.Open("c:\\test.txt");
            // Use file.
        }
        catch(Exception e)
        {
            Console.WriteLine(e.StackTrace);
        }
    }
}

In this example, what prints out is the following:

at StackTraceTest.Main()

Therefore, the StackTrace property returns the call stack at the point that the exception is caught, which can be useful for logging and debugging scenarios.

Catching Multiple Exception Types:

try
{
    Foo(); // Can throw FooException.
    Bar(); // Can throw BarException.
}
catch(FooException e)
{
    // Handle the error.
}
catch(BarException e)
{
    // Handle the error.
}

catch(Exception e)
{
}

the base class is handled last.

 

6. Build Exception Classes

To name your exception classes such that the name ends with the word “Exception.”  Eg: MyWorkException.

Implement all three System.Exception constructors.

using System;

public class TestException : Exception

{
    // You would probably have extra methods and properties
    // here that augment the .NET Exception that you derive from.

    // Base Exception class constructors.
    public TestException()
        :base() {}
    public TestException(String message)
        :base(message) {}
    public TestException(String message, Exception innerException)
        :base(message, innerException) {}
}
public class DerivedExceptionTestApp
{
    public static void ThrowException()
    {
        throw new TestException("error condition");
    }
    public static void Main()
    {
        try
        {
            ThrowException();
        }
        catch(Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }
}

Note that the ToString method results in a combination of properties being displayed: the textual representation of the exception class name, the message string passed to the exception’s constructor, and the StackTrace.

TestException: error condition
   at DerivedExceptionTestApp.Main()
7.

using System;

class WhenToCatchApp
{
    public void Foo()
    {
        try
        {
            Bar();
        }
        catch(Exception e)
        {
            Console.WriteLine(e.Message);
        }
    }

    public void Bar()
    {
        try
        {
            // Call method to set a "commitment boundary."
            Console.WriteLine("setting commitment boundary");

            // Call Baz to save data.
            Console.WriteLine("calling Baz to save data");
            Baz();

            Console.WriteLine("commiting saved data");
        }
        catch(Exception)
        {
                // In this case, Bar should catch the exception 
                // because it's doing something significant 
                //(rolling back uncommitted database changes).

                Console.WriteLine("rolling back uncommited changes " +

                         "and then rethrowing exception");

            throw;
        }
    }

    public void Baz()
    {
        throw new Exception("db failure in Baz");
    }

    public static void Main()
    {
        WhenToCatchApp test = new WhenToCatchApp();
        test.Foo(); // This method will ultimately print
                    // the error msg.
    }
}

Advertisements
This entry was posted in C#. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s