Prev | Current Page 364 | Next

Jon Skeet

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

Reverse(chars);
return new string(chars);
}
}
The private constructor B may seem odd??”why have it at all if it??™s private and never
going to be used? The reason is that if you don??™t supply any constructors for a class, the
C# 1 compiler will always provide a default constructor that is public and parameterless. In
this case, we don??™t want any visible constructors, so we have to provide a private one.
This pattern works reasonably well, but C# 2 makes it explicit and actively prevents
the type from being misused. First we??™ll see what changes are needed to turn listing 7.3
into a ???proper??? static class as defined in C# 2. As you can see from listing 7.4, very little
action is required.
using System;
public static class StringHelper
{
public static string Reverse(string input)
{
char[] chars = input.ToCharArray();
Array.Reverse(chars);
return new string(chars);
}
}
We??™ve used the static modifier in the class declaration this time instead of sealed,
and we haven??™t included a constructor at all??”those are the only code differences. The
C# 2 compiler knows that a static class shouldn??™t have any constructors, so it doesn??™t
provide a default one. In fact, the compiler enforces a number of constraints on the
class definition:
?–  It can??™t be declared as abstract or sealed, although it??™s implicitly both.
?–  It can??™t specify any implemented interfaces.


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