Escolar Documentos
Profissional Documentos
Cultura Documentos
M I CRO S O F T
L EA RN I N G
2124C
Programming with C#
Companion Content
PRO DU C T
Information in this document, including URL and other Internet Web site references, is subject to change
without notice. Unless otherwise noted, the example companies, organizations, products, domain names,
e-mail addresses, logos, people, places, and events depicted herein are fictitious, and no association with
any real company, organization, product, domain name, e-mail address, logo, person, place or event is
intended or should be inferred. Complying with all applicable copyright laws is the responsibility of the
user. Without limiting the rights under copyright, no part of this document may be reproduced, stored in
or introduced into a retrieval system, or transmitted in any form or by any means (electronic, mechanical,
photocopying, recording, or otherwise), or for any purpose, without the express written permission of
Microsoft Corporation.
Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual property
rights covering subject matter in this document. Except as expressly provided in any written license
agreement from Microsoft, the furnishing of this document does not give you any license to these
patents, trademarks, copyrights, or other intellectual property.
The names of manufacturers, products, or URLs are provided for informational purposes only and
Microsoft makes no representations and warranties, either expressed, implied, or statutory, regarding
these manufacturers or the use of the products with any Microsoft technologies. The inclusion of a
manufacturer or product does not imply endorsement of Microsoft of the manufacturer or product. Links
may be provided to third party sites. Such sites are not under the control of Microsoft and Microsoft is not
responsible for the contents of any linked site or any link contained in a linked site, or any changes or
updates to such sites. Microsoft is not responsible for webcasting or any other form of transmission
received from any linked site. Microsoft is providing these links to you only as a convenience, and the
inclusion of any link does not imply endorsement of Microsoft of the site or the products contained
therein.
2001-2002 Microsoft Corporation. All rights reserved.
Microsoft and the trademarks listed at
http://www.microsoft.com/about/legal/en/us/IntellectualProperty/Trademarks/EN-US.aspx are trademarks
of the Microsoft group of companies. All other marks are property oftheir respective owners.
Module 1
Overview of the Microsoft .NET Platform
Contents:
Questions and Answers
1-1
1-2
Programming with C#
2.
3.
4.
5.
6.
7.
Overview of C#
Module 2
Overview of C#
Contents:
Questions and Answers
2-1
2-2
Programming with C#
2.
3.
4.
5.
6.
7.
What happens if your C# application causes an exception to be thrown that it is not prepared to
catch?
Answer: If your application causes an exception to be thrown and it is not prepared to catch it,
common language runtime will display a dialog box to the user that can be used to invoke the
debugger.
Module 3
Using Value-Type Variables
Contents:
Questions and Answers
3-1
3-2
Programming with C#
2.
3.
4.
Module 4
Statements and Exceptions
Contents:
Questions and Answers
4-1
4-2
Programming with C#
Write an if statement that tests whether an int variable called hour is greater than or equal to zero
and less than 24. If it is not, reset hour to zero.
Answer:
if (hour < 0 || hour >= 24) {
hour = 0;
}
2.
Write a do-while statement, the body of which reads an integer from the console and stores it in an
int called hour. Write the loop so that the loop will exit only when hour has a value between 1 and 23
(inclusive).
Answer:
int hour;
do {
Console.Write("Enter the hour: ");
hour = int.Parse(Console.ReadLine( ));
} while (hour < 0 || hour >= 24);
3.
Write a for statement that meets all of the conditions of the preceding question and only allows five
attempts to input a valid value for hour. Do not use break or continue statements.
Answer:
int hour = 0;
bool valid = false;
for (int attempts = 0; attempts < 5 && !valid; attempts++) {
Console.Write("Enter the hour: ");
hour = int.Parse(Console.ReadLine( ));
valid = (hour >= 0 && hour < 24);
}
if (valid)
Console.WriteLine(hour);
else
Console.WriteLine("No valid hour entered.");
4.
Rewrite the code that you wrote for question 3, but this time use a break statement.
Answer:
int hour = 0;
for (int attempts = 0; attempts < 5; attempts++) {
Console.Write("Enter the hour: ");
hour = int.Parse(Console.ReadLine( ));
if (hour >= 0 && hour < 24)
break;
}
if (hour >= 0 && hour < 24)
Console.WriteLine(hour);
else
Console.WriteLine("No valid hour entered.");
5.
4-3
6.
The following code is meant to handle exceptions Explain why this code is not correct. Fix the
problem.
try
{
...
}
catch (Exception) {...}
catch (IOException) {...}
Answer: The code generates a compile time error because the most general exception is
caught first. To correct the problem, catch the IOException first and then catch the Exception.
Module 5
Methods and Parameters
Contents:
Questions and Answers
5-1
5-2
Programming with C#
2.
List the three ways in which data can be passed in parameters, and the associated C# keywords.
Answer:
Pass by value (default)
Pass by reference (ref)
Output (out)
3.
4.
What keyword should be added to a method definition if the method needs to be called from
another class?
Answer: public
5.
6.
Define the signature of a static method called Rotate that does not return a value but that must
"right rotate" its three integer parameters.
Answer: static void Rotate(ref int first, ref int second, ref int third)
Arrays
Module 6
Arrays
Contents:
Questions and Answers
6-1
6-2
Programming with C#
Declare an array of ints of rank 1 called evens, and initialize it with the first five even numbers,
starting with zero.
Answer:
int[ ] evens = { 0, 2, 4, 6, 8 };
2.
Write a statement that declares variable called crowd of type int, and initialize it with the second
element of evens. Remember, the second element does not reside at index 2 because array indexes
do not start at 1.
Answer:
int crowd = evens[1];
3.
Write two statements. The first will declare an array of ints of rank 1 called copy; the second will
assign to copy from evens.
Answer:
int[ ] copy;
copy = evens;
4.
Write a static method called Method that returns an array of ints of rank 2 and expects no
arguments. The body of Method will contain a single return statement. This statement returns a
newly created array of rank 2 with dimensions 3 and 5 whose 15 elements are all initialized to 42.
Answer:
static int[,] Method( ) {
return new int[3,5] {
{ 42, 42, 42, 42, 42 },
{ 42, 42, 42, 42, 42 },
{ 42, 42, 42, 42, 42 }
};
}
5.
Write a static method called Parameter that returns nothing and expects a two-dimensional array as
its single argument. The body of the method will contain two WriteLine statements that write the
length of each dimension to the console.
Answer:
static void Parameter(int[,] array) {
System.Console.WriteLine(array.GetLength(0));
System.Console.WriteLine(array.GetLength(1));
}
6.
Write a foreach statement that iterates over a one-dimensional array of strings called names, writing
each name to the console.
Answer:
foreach (string name in names) {
System.Console.WriteLine(name);
}
Module 7
Essentials of Object-Oriented Programming
Contents:
Questions and Answers
7-1
7-2
Programming with C#
2.
3.
4.
5.
Describe the differences between interfaces, abstract classes, and concrete classes.
Answer: An interface contains only operations and no implementation. You cannot create an
instance of an interface. An interface exists solely to be derived from.
An abstract base class is like an interface in that you cannot create an instance of an abstract
base class. A base class exists solely to be derived from. Unlike an interface, an abstract base
class can contain some implementation. Abstract base classes are often created to capture
common implementation details of concrete classes.
A concrete class can be used to create new objects. A concrete class must implement all
operations inherited from its abstract base classes and interfaces.
Module 8
Using Reference-Type Variables
Contents:
Questions and Answers
Multimedia
8-1
8-2
Programming with C#
Explain how a memory is allocated and de-allocated for a variable of reference type.
Answer: A variable of reference type holds a reference to the object in memory. The object is
allocated when the new operator is used.
2.
What special value indicates that a reference variable does not contain a reference to an object? What
happens if you try to access a reference variable with this value?
Answer: The special value is null. A NullReferenceException is thrown if you try to access a
reference variable with this value.
3.
4.
5.
Explain the difference between the cast operator and the as operator when used to convert between
class references.
Answer: If the reference cannot be converted to the target type, the cast operator will throw
an InvalidCastException, but the as operator will return null.
6.
Multimedia
M edia Type
Title
Animation
Typesafe Casting
8-3
Module 9
Creating and Destroying Objects
Contents:
Questions and Answers
9-1
9-2
Programming with C#
Declare a class called Date with a public constructor that expects three int parameters called year,
month, and day.
Answer:
class Date
{
public Date(int year, int month, int day)
{
...
}
}
2.
Will the compiler generate a default constructor for the Date class that you declared in question 1?
What if Date were a struct with the same three-int constructor?
Answer: The compiler will only generate a constructor for a class if the class does not have a
constructor of its own. Since the Date class in question 1 does have a constructor, the compiler
will not generate a default constructor for the Date class.
If Date were a struct, the compiler would generate a default constructor. The compiler always
generates a default constructor for a struct.
3.
Which method does garbage collection call on the object just before it recycles the object's memory
back to the heap?
Answer: If a Dispose method is not called on an object before garbage collection starts,
garbage collection calls a destructor (if available) on the object some time before recycling the
object's memory back to the heap.
4.
Inheritance in C#
Module 10
Inheritance in C#
Contents:
Questions and Answers
10-1
10-2
Programming with C#
Create a class called Widget that declares two public methods. Create both methods so that they
return void and so that they do not use parameters. Call the first method First, and declare it as
virtual. Call the second method Second, and do not declare it as virtual. Create a class called
FancyWidget that extends Widget, overriding the inherited First method and hiding the inherited
Second method.
Answer:
class Widget
{
public virtual void First( ) { ... }
public void Second( ) { ... }
}
class FancyWidget: Widget
{
public override void First( ) { ... }
new public void Second( ) { ... }
}
2.
Create an interface called IWidget that declares two methods. Create both methods so that they
return void and so that they do not use parameters. Call the first method First, and call the second
method Second. Create a class called Widget that implements IWidget.Implement First as virtual,
and implement Second explicitly.
Answer:
interface IWidget
{
void First( );
void Second( );
}
class Widget: IWidget
{
public virtual void First( ) { ... }
void IWidget.Second( ) { ... }
}
3.
Create an abstract class called Widget that declares a protected abstract method called First that
returns void and does not use parameters. Create a class called FancyWidget that extends Widget,
overriding the inherited First method.
Answer:
abstract class Widget
{
protected abstract void First( );
}
class FancyWidget: Widget
{
protected override void First( ) { ... }
}
4.
Create a sealed class called Widget that implements the IWidget interface that you created in
question 2. Create Widget so that it implements both inherited methods explicitly.
Answer:
Inheritance in C#
interface IWidget
{
void First( );
void Second( );
}
sealed class Widget: IWidget
{
void IWidget.First( ) { ... }
void IWidget.Second( ) { ... }
}
10-3
Module 11
Aggregation, Namespaces, and Advanced Scope
Contents:
Questions and Answers
11-1
11-2
Programming with C#
Imagine that you have two .cs files. The alpha.cs file contains a class called Alpha that contains an
internal method called Method. The beta.cs file contains a class called Beta that also contains an
internal method called Method. Can Alpha.Method be called from Beta.Method, and vice versa?
Answer: It depends. Internal access specifies assembly-level access. Alpha.Method and
Beta.Method can call each other only if Alpha and Beta are located in the same assembly.
2.
3.
Outer.Inner
Wibble { }
Test
Outer.Inner;
SpecialWibble: Inner.Wibble { }
Answer: No. There is an error. The using-namespace-directive brings the names that are inside
Outer.Inner into scope. It does not bring the name Inner itself into scope. Hence, the use of
Inner.Widget as a base class for SpecialWidget is an error because the compiler cannot resolve
the identifier Inner.
4.
Module 12
Operators, Delegates, and Events
Contents:
Questions and Answers
12-1
12-2
Programming with C#
Can the arithmetic compound assignment operators (+=, -=, *=, /=, and %=) be overloaded?
Answer: Not directly, but they are evaluated in terms of the basic binary arithmetic operators
(+, -, *, /, and %), which can be overloaded. For example,
A += B
is evaluated as
A = A + B
3.
4.
What is a delegate?
Answer: A delegate is a reference to a method. If a delegate is invoked, the method referred to
by the delegate is executed. The method a delegate refers to can be changed dynamically, so a
call to the same delegate could execute different methods at different times.
5.
6.
In what order are the methods that subscribe to an event called? Will all methods that subscribe to an
event always be executed?
Answer: You cannot guarantee the order in which the methods will be called. If one of the
subscribing methods throws an exception, it is possible that other subscribing methods may
not be executed at all.
Module 13
Properties and Indexers
Contents:
Questions and Answers
13-1
13-2
Programming with C#
Declare a Font class that contains a read-only property called Name of type string.
Answer:
class Font
{
private string name;
public string Name
{
get { return name; }
}
}
2.
Declare a DialogBox class that contains a read/write property called Caption of type string.
Answer:
class DialogBox
{
public string Caption
{
get { return caption; }
set { caption = value; }
}
private string caption;
}
3.
Declare a MutableString class that contains a read/write indexer of type char that expects a single
int parameter.
Answer:
class MutableString
{
public MutableString(string src)
{
chars = new char[src.Length];
for (int i = 0; i < src.Length; i++ ) {
chars[i] = src[i];
}
}
public char this[int index]
{
get { return chars[index]; }
set { chars[index] = value; }
}
private char[ ] chars;
}
4.
Declare a Graph class that contains a read-only indexer of type double that expects a single
parameter of type Point.
Answer:
class Graph
{
public double this[Point p]
{
get { ... }
}
13-3
Attributes
Module 14
Attributes
Contents:
Questions and Answers
14-1
14-2
Programming with C#
2.
3.
4.
Define an attribute class called CodeTestAttributes that is applicable only to classes. It should have
no positional parameters and two named parameters called Reviewed and HasTestSuite. These
parameters should be of type bool and should be implemented by using read/write properties.
Answer:
using System;
[AttributeUsage(AttributeTargets.Class)]
public class CodeTestAttributes: System.Attribute
{
public bool Reviewed
{
get { return reviewed; }
set { reviewed = value; }
}
public bool HasTestSuite
{
get { return hasTestSuite; }
set { hasTestSuite = value; }
}
private bool reviewed, hasTestSuite;
}
5.
Define a class called Widget, and use CodeTestAttributes from the previous question to mark that
Widget has been reviewed but has no test suite.
Answer:
[CodeTestAttributes(Reviewed=true, HasTestSuite=false)]
class Widget
{
...
}
6.
Suppose that Widget from the previous question had a method called LogBug. Could
CodeTestAttributes be used to mark only this method?
Answer: No. CodeTestAttributes can only target whole classes.
Programming with C#
Resources
Contents:
Internet Links
R-1
R-2
Programming with C#
Internet Links
The Web sites listed below provide additional resources.
C# Development Resources
Web Site
URL
.NET Wire
http://www.dotnetwire.com
Discuss.Develop.com http://discuss.develop.com
C# Help
http://www.csharphelp.com
C# Station
http://www.csharp-station.com
Csharpindex
http://www.csharpindex.com
CodeHound C#
http://www.codehound.com/csharp
C# Corner
http://www.c-sharpcorner.com
URL
Microsoft .NET
http://www.microsoft.com/net/
Microsoft .NET
Developer Center
http://msdn.microsoft.com/net/
GotDotNet Home
Page
http://www.gotdotnet.com/
URL
Microsoft .NET:
Realizing the Next
Generation Internet
http://www.microsoft.com/business/vision/netwhitepaper.asp
Microsoft .NET
Framework FAQ
http://msdn.microsoft.com/library/techart/faq111700.htm
C# Language
Specification
http://msdn.microsoft.com/vstudio/nextgen/technology/csharpdownload.asp
C# Introduction and
Overview
http://msdn.microsoft.com/vstudio/nextgen/technology/csharpintro.asp
Programming with C#
R-3
Note Not all training products will have a Knowledge Base article if that is the case, please ask your
instructor whether or not there are existing error log entries.
Courseware Feedback
Send all courseware feedback to support@mscourseware.com. We truly appreciate your time and effort.
We review every e-mail received and forward the information on to the appropriate team. Unfortunately,
because of volume, we are unable to provide a response but we may use your feedback to improve your
future experience with Microsoft Learning products.
Reporting Errors
When providing feedback, include the training product name and number in the subject line of your email. When you provide comments or report bugs, please include the following:
Please provide any details that are necessary to help us verify the issue.
Important All errors and suggestions are evaluated, but only those that are validated are added to the
product Knowledge Base article.