Skip to Main Content
C# Cookbook, 2nd Edition
book

C# Cookbook, 2nd Edition

by Jay Hilyard, Stephen Teilhet
January 2006
Intermediate to advanced content levelIntermediate to advanced
1184 pages
43h 23m
English
O'Reilly Media, Inc.
Content preview from C# Cookbook, 2nd Edition
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Introduction
|
369
to be thrown. Remember that throwing an exception has a negative impact on per-
formance, whereas exception-handling code has a minimal impact on performance,
as long as an exception is not thrown.
To illustrate this, here is a method that uses exception-handling code to process the
NullReferenceException:
public void SomeMethod( )
{
try
{
Stream s = GetAnyAvailableStream( );
Console.WriteLine("This stream has a length of " + s.Length);
}
catch (Exception e)
{
// Handle a null stream here.
}
}
Here is the method implemented to use an if-else conditional instead:
public void SomeMethod( )
{
Stream s = GetAnyAvailableStream( );
if (s != null)
{
Console.WriteLine("This stream has a length of " + s.Length);
}
else
{
// Handle a null stream here.
}
}
Additionally, you should also make sure that this stream is closed by using the
finally block in the following manner:
public void SomeMethod( )
{
Stream s = null;
try
{
s = GetAnyAvailableStream( );
if (s != null)
{
Console.WriteLine("This stream has a length of " + s.Length);
}
else
{
// Handle a null stream here.
}
}
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved. ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C# Cookbook

C# Cookbook

Joe Mayo
C# Cookbook

C# Cookbook

Stephen Teilhet, Jay Hilyard
Head First C#, 4th Edition

Head First C#, 4th Edition

Andrew Stellman, Jennifer Greene

Publisher Resources

ISBN: 0596100639Supplemental ContentCatalog PageErrata