You are on page 1of 2

IT528

Developing .NET Applications Using C#

May 9, 2009 Spring 2008-2009


PART 1

FINAL SOLUTIONS

Duration: 30 minutes (9 points)

1. Explain at least 3 benefits of exceptions that you can think of.

The ability to keep code that deals with exceptional situations in a central place. The ability to keep cleanup code in a dedicated location and making sure this cleanup code will execute. They provide a unified error handling mechanism for all .NET libraries as well as user-designed classes. The caller could ignore the error returned by a Win32 API, now the caller cannot continue with exceptions. If the application cannot handle the exception, CLR can terminate the application. Old Win32 APIs and COM returns a 32-bit error code. Exceptions include a string description of the problem. Exceptions also include a stack trace that tells you the path application took until the error occurred. You can also put any information you want in a user-defined exception of your own.

2. What are is and as operators? Why do we need them? Show an example.

(10 points)

They are used to downcast a type to another. When downcasting an object, a System.InvalidCastException occurs if at execution time the object does not have an isa relationship with the type specified in the cast operator. An object can be cast only to its own type or to the type of one of its base classes. You can avoid a potential InvalidCastExceptionby using the asoperator to do a downcast rather than a cast operator. If the downcast is invalid, the expression will be null instead of throwing an exception. Before performing a cast from a base-class object to a derived-class object, use theisoperator to ensure that the object is indeed an object of an appropriate derived-class type.

XNode node; XElement element;

// XElement derives from XContainer // and XContainer derives from XNode

element = node as XElement; if (element != null) return '<' + element.Name.LocalName + '>'; // same code with is this time. if (node is XElement) // now we can safely downcast return '<' + ((XElement)node).Name.LocalName + '>';

IT528
Developing .NET Applications Using C# 3. Write the prototype of a generic Stack class. Assume the class has a constructor that takes an IEnumerable interface as the parameter for the initial collection of elements to fill the stack with. And the class has the Push and Pop methods. Just give the header of the methods, not their implementations. (10 points)

public class Stack<T> { public Stack(IEnumerable<T> collection) { } public T Pop() { } public void Push(T item) { } }

You might also like