C#
Boolean
ToString
Programming
Case Sensitivity

Why does Boolean.ToString output True and not true

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Boolean values are essential primitives in many programming languages, including C#. They have two possible values: true and false , which are used to perform logical operations and control flow. In C#, the ToString method on a Boolean value outputs "True" for true values and "False" for false values. This might spur some curiosity, as one might expect a direct string conversion to match the language-specific literal true . Here’s a detailed look at why this is designed to behave the way it does.

Boolean.ToString Implementation in C#

Technical Explanation

The Boolean.ToString() method in C# converts the value of a Boolean instance (“true” or “false”) to a string representation of "True" or "False" . To understand why it capitalizes the first letter, it's helpful to delve into a few related areas:

  1. CLS Compliance:
    • The .NET framework is designed to be Common Language Specification (CLS) compliant. This compliance ensures interoperability among .NET languages. In many natural languages, True and False are often written capitalized, which aligns better with user expectations, especially in display contexts.
  2. Consistency with Other Types:
    • Integral and floating-point types also have a ToString method in which the output of special values like NaN or Infinity is capitalized (e.g., Double.NaN returns "NaN" and not "nan" ). Thus, it's consistent across different types.
  3. Historical Context:
    • The early design decisions for .NET considered usability for developers across different backgrounds, ensuring a standard appearance when displaying logical values in UI such as forms, reports, and logs.

Example

Consider the following example in C#:

  • If your application is localized, consider how Boolean values are represented in different locales. The approach to capitalize or not could depend on the conventions and norms of the target audience.
  • When using these methods for logging, debugging, or user interfaces, ensure that the semantic meaning of the values is correctly and clearly communicated to the users, regardless of capitalization.

Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.