Prev | Current Page 365 | Next

Jon Skeet

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


?–  It can??™t specify a base type.
?–  It can??™t include any nonstatic members, including constructors.
?–  It can??™t include any operators.
?–  It can??™t include any protected or protected internal members.
It??™s worth noting that although all the members have to be static, you??™ve got to explicitly
make them static except for nested types and constants. Although nested types are
implicitly static members of the enclosing class, the nested type itself can be a nonstatic
type if that??™s required.
The compiler not only puts constraints on the definition of static classes, though??”
it also guards against their misuse. As it knows that there can never be any instances of
Listing 7.4 The same utility class as in listing 7.3 but converted into a C# 2 static class
All methods
are static
192 CHAPTER 7 Concluding C# 2: the final features
the class, it prevents any use of it that would require one. For instance, all of the following
are invalid when StringHelper is a static class:
StringHelper variable = null;
StringHelper[] array = null;
public void Method1(StringHelper x) {}
public StringHelper Method1() { return null; }
List x = new List();
None of these are prevented if the class just follows the C# 1 pattern??”but all of them
are essentially useless. In short, static classes in C# 2 don??™t allow you to do anything you
couldn??™t do before??”but they prevent you from doing things that you shouldn??™t have
been doing anyway.


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