Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is TextWriter.Write(char) not abstract?

Tags:

c#

.net

TextWriter is an abstract class with one abstract function - Encoding Encoding { get; }. Implementations must also implement void Write(char), but this function is not abstract - why? The default implementation does nothing which for me does not make sense.

like image 524
larsmoa Avatar asked Aug 22 '14 12:08

larsmoa


1 Answers

It's a design error in TextWriter. According to Reflector, all other Write* methods reduce to Write(char). The documentation says something similar. Write(char) should be abstract.

A developer not noticing this might be mislead to create an implementation that mostly works, but when writing a char (which is uncommon) it might do nothing. Surprising behavior.

If you derive from TextWriter and you know that callers will only use certain overloads such as Write(string) you can save some work by only overriding the necessary methods and ignoring Write(char). That, however, violates the Liskov substitution principle. Back when the BCL was designed they might not have taken a strict stance on the SOLID principles.

The reference source is not enlightening:

    // Writes a character to the text stream. This default method is empty,
    // but descendant classes can override the method to provide the
    // appropriate functionality.
    //
    public virtual void Write(char value) {
    }
like image 143
usr Avatar answered Oct 21 '22 21:10

usr