Prev | Current Page 363 | Next

Jon Skeet

"C# in Depth: What you need to master C# 2 and 3"


Everyone has utility classes. I haven??™t seen a significant project in either Java or C#
that didn??™t have at least one class consisting solely of static methods. The classic example
appearing in developer code is a type with string helper methods, doing anything
from escaping, reversing, smart replacing??”you name it. An example from the Framework
is the System.Math class. The key features of a utility class are as follows:
?–  All members are static (except a private constructor).
?–  The class derives directly from object.
?–  Typically there??™s no state at all, unless there??™s some caching or a singleton
involved.
?–  There are no visible constructors.
?–  The class is sealed if the developer remembers to do so.
The last two points are optional, and indeed if there are no visible constructors
(including protected ones) then the class is effectively sealed anyway. Both of them help
make the purpose of the class more obvious, however.
Listing 7.3 gives an example of a C# 1 utility class??”then we??™ll see how C# 2
improves matters.
using System;
public sealed class StringHelper
{
private StringHelper()
{
}
Listing 7.3 A typical C# 1 utility class
Seals class to
prevent derivation
B
Prevents instantiation
from other code
191 Static classes
public static string Reverse(string input)
{
char[] chars = input.ToCharArray();
Array.


Pages:
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375