.NET HELP

Humanizer C# (How It Works For Developers)

Chipego
Chipego Kalinda
July 1, 2024
Share:

Humanizer is a powerful and flexible .NET library that simplifies and humanizes the process of working with data, especially when it comes to displaying information in a user-friendly format. Whether you need to convert dates to relative time strings ("3 days ago"), pluralize words, format numbers as words, or work with enums, displaying strings, Pascal case input strings as sentences with custom descriptions, underscored input strings to normal title case strings, and long text truncation, Humanizer provides a plethora of tools and extension methods to handle these tasks elegantly in C#.NET to convert dehumanized input strings into sentences.

In this article, we will discuss a detailed tutorial of Humanizer in C#. We will also discuss how to generate PDF documents using Humanizer and IronPDF for C# PDF Library.

Setting Up Humanizer in C#

To get started with Humanizer, you need to install the library via NuGet. In your project, you can do this through the Package Manager Console with the following command:

Install-Package Humanizer
Install-Package Humanizer

Alternatively, if you are using the .NET Core CLI, you can add Humanizer with:

dotnet add package Humanizer

After installation, you can start using Humanizer by including the appropriate namespace in your C# files:

using Humanizer;
using Humanizer;

Humanizing Dates and Times

One of the most common uses of Humanizer is to convert dates and times into human-readable formats, timespans, numbers, and quantities using the Humanize method. This is particularly useful for displaying relative times, such as "2 hours ago" or "in 5 days".

Example: Humanizing Relative Time

DateTime pastDate = DateTime.Now.AddDays(-3);
string humanizedTime = pastDate.Humanize(); // Output: "3 days ago"
DateTime futureDate = DateTime.Now.AddHours(5);
string futureHumanizedTime = futureDate.Humanize(); // Output: "in 5 hours"
DateTime pastDate = DateTime.Now.AddDays(-3);
string humanizedTime = pastDate.Humanize(); // Output: "3 days ago"
DateTime futureDate = DateTime.Now.AddHours(5);
string futureHumanizedTime = futureDate.Humanize(); // Output: "in 5 hours"

The Humanizer extension method automatically handles different time units and even adjusts for grammatical correctness.

Humanizer C# (How It Works For Developers): Figure 1 - Humanizing Relative Time Output

Humanizing TimeSpans

Humanizer can also humanize TimeSpan objects, making it easy to display durations in a readable format.

Example: Humanizing TimeSpan

TimeSpan timeSpan = TimeSpan.FromMinutes(123);
string humanizedTimeSpan = timeSpan.Humanize(2); // Output: "2 hours, 3 minutes"
TimeSpan timeSpan = TimeSpan.FromMinutes(123);
string humanizedTimeSpan = timeSpan.Humanize(2); // Output: "2 hours, 3 minutes"

Humanizer C# (How It Works For Developers): Figure 2 - Humanizing TimeSpan Output

Working with Numbers

Humanizer provides several methods to convert numbers into human-readable words and to handle ordinal numbers.

Example: Converting Numbers to Words

int number = 123;
string words = number.ToWords(); // Output: "one hundred and twenty-three"
int number = 123;
string words = number.ToWords(); // Output: "one hundred and twenty-three"

Humanizer C# (How It Works For Developers): Figure 3 - Number to Word Output

Example: Converting Numbers to Ordinals

int number = 21;
string ordinal = number.ToOrdinalWords(); // Output: "twenty-first"
int number = 21;
string ordinal = number.ToOrdinalWords(); // Output: "twenty-first"

Humanizer C# (How It Works For Developers): Figure 4 - Number to Ordinal Output

Pluralization and Singularization

Humanizer makes it easy to convert words between their singular and plural forms, which is useful for dynamically generating long text based on quantity.

Example: Pluralizing and Singularizing Words

string singular = "car";
string plural = singular.Pluralize(); // Output: "cars"
string word = "people";
string singularForm = word.Singularize(); // Output: "person"
string singular = "car";
string plural = singular.Pluralize(); // Output: "cars"
string word = "people";
string singularForm = word.Singularize(); // Output: "person"

Humanizer handles irregular pluralizations and singularizations as well, making it robust for various use cases.

Humanizer C# (How It Works For Developers): Figure 5 - Pluralize and Singularize Output

Formatting Enums

Enums are frequently used in C# applications to represent a set of named constants. Humanizer can convert enum values to human-readable strings.

Example: Humanizing Enums

MyEnum enumValue = MyEnum.FirstValue;
string humanizedEnum = enumValue.Humanize();
System.Console.WriteLine(humanizedEnum);
public enum MyEnum
{
    FirstValue,
    SecondValue
} // Output: "First value"
MyEnum enumValue = MyEnum.FirstValue;
string humanizedEnum = enumValue.Humanize();
System.Console.WriteLine(humanizedEnum);
public enum MyEnum
{
    FirstValue,
    SecondValue
} // Output: "First value"

This method can be particularly useful for displaying user-friendly labels in UIs.

Humanizer C# (How It Works For Developers): Figure 6 - Humanize Enum Output

Humanizing Byte Sizes

Another handy feature of Humanizer is the ability to humanize byte sizes, converting large byte values into readable formats like KB, MB, or GB.

Example: Humanizing Byte Sizes

long bytes = 1048576;
string humanizedBytes = bytes.Bytes().Humanize(); // Output: "1 MB"
long bytes = 1048576;
string humanizedBytes = bytes.Bytes().Humanize(); // Output: "1 MB"

Humanizer C# (How It Works For Developers): Figure 7 - Humanizing Byte Size Output

Advanced Scenarios

Humanizer is not limited to the basic scenarios described above. It supports a wide range of advanced features such as the Truncate method and multiple languages and extensions.

Example: Humanizing DateTime Offsets

Humanizer can also handle DateTimeOffset, which is useful for applications dealing with time zones.

DateTimeOffset dateTimeOffset = DateTimeOffset.Now.AddDays(-2);
string humanizedDateTimeOffset = dateTimeOffset.Humanize(); // Output: "2 days ago"
DateTimeOffset dateTimeOffset = DateTimeOffset.Now.AddDays(-2);
string humanizedDateTimeOffset = dateTimeOffset.Humanize(); // Output: "2 days ago"

Humanizer C# (How It Works For Developers): Figure 8 - Humanizing DateTime Offset Output

Performance Considerations

Humanizer is designed to be efficient, but like any library, its performance depends on how it is used. For applications requiring high performance, especially those dealing with large datasets or real-time processing, it is essential to consider the impact of frequent humanization operations.

IronPDF for C

IronPDF is a comprehensive PDF generation and manipulation library for .NET applications. It enables developers to create, read, edit, and extract content from PDF files with ease. IronPDF is designed to be user-friendly, offering a wide range of functionalities including converting HTML to PDF, merging documents, adding watermarks, and much more. Its versatility and powerful features make it an excellent choice for handling PDF documents in C# projects.

Installing IronPDF via NuGet Package Manager

Follow these steps to install IronPDF using the NuGet Package Manager:

  1. Open Your Project in Visual Studio:

    • Launch Visual Studio and open your existing C# project or create a new one.
  2. Open the NuGet Package Manager:

    • Right-click on your project in the Solution Explorer.
    • Select "Manage NuGet Packages…" from the context menu.

Humanizer C# (How It Works For Developers): Figure 9 - NuGet Package Manager

  1. Install IronPDF:

    • In the NuGet Package Manager, go to the "Browse" tab.
    • Search for IronPDF.
    • Select the IronPDF package from the search results.
    • Click the "Install" button to add IronPDF to your project.

Humanizer C# (How It Works For Developers): Figure 10 - IronPDF

By following these steps, IronPDF will be installed and ready to use in your C# project, allowing you to leverage its powerful PDF manipulation capabilities.

C# Humanizer and IronPDF Code Example

using Humanizer;
using IronPdf;
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // Instantiate Renderer
        var renderer = new ChromePdfRenderer();
        List<string> content = GenerateHumanizedContent();
        string htmlContent = "<h1>Humanizer Examples</h1><ul>";

        // Iterate over each item in the List and add it to the HTML string
        foreach (var item in content)
        {
            htmlContent += $"<li>{item}</li>";
        }
        htmlContent += "</ul>";

        // Create a PDF from an HTML string using C#
        var pdf = renderer.RenderHtmlAsPdf(htmlContent);

        // Export to a file or stream
        pdf.SaveAs("output.pdf");
    }

    static List<string> GenerateHumanizedContent()
    {
        List<string> content = new List<string>();

        // DateTime examples
        DateTime pastDate = DateTime.Now.AddDays(-3);
        DateTime futureDate = DateTime.Now.AddHours(5);
        content.Add($"DateTime.Now: {DateTime.Now}");
        content.Add($"3 days ago: {pastDate.Humanize()}");
        content.Add($"In 5 hours: {futureDate.Humanize()}");

        // TimeSpan examples
        TimeSpan timeSpan = TimeSpan.FromMinutes(123);
        content.Add($"TimeSpan of 123 minutes: {timeSpan.Humanize()}");

        // Number examples
        int number = 12345;
        content.Add($"Number 12345 in words: {number.ToWords()}");
        content.Add($"Ordinal of 21: {21.ToOrdinalWords()}");

        // Pluralization examples
        string singular = "car";
        content.Add($"Plural of 'car': {singular.Pluralize()}");
        string plural = "children";
        content.Add($"Singular of 'children': {plural.Singularize()}");

        // Byte size examples
        long bytes = 1048576;
        content.Add($"1,048,576 bytes: {bytes.Bytes().Humanize()}");

        return content;
    }
}
using Humanizer;
using IronPdf;
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // Instantiate Renderer
        var renderer = new ChromePdfRenderer();
        List<string> content = GenerateHumanizedContent();
        string htmlContent = "<h1>Humanizer Examples</h1><ul>";

        // Iterate over each item in the List and add it to the HTML string
        foreach (var item in content)
        {
            htmlContent += $"<li>{item}</li>";
        }
        htmlContent += "</ul>";

        // Create a PDF from an HTML string using C#
        var pdf = renderer.RenderHtmlAsPdf(htmlContent);

        // Export to a file or stream
        pdf.SaveAs("output.pdf");
    }

    static List<string> GenerateHumanizedContent()
    {
        List<string> content = new List<string>();

        // DateTime examples
        DateTime pastDate = DateTime.Now.AddDays(-3);
        DateTime futureDate = DateTime.Now.AddHours(5);
        content.Add($"DateTime.Now: {DateTime.Now}");
        content.Add($"3 days ago: {pastDate.Humanize()}");
        content.Add($"In 5 hours: {futureDate.Humanize()}");

        // TimeSpan examples
        TimeSpan timeSpan = TimeSpan.FromMinutes(123);
        content.Add($"TimeSpan of 123 minutes: {timeSpan.Humanize()}");

        // Number examples
        int number = 12345;
        content.Add($"Number 12345 in words: {number.ToWords()}");
        content.Add($"Ordinal of 21: {21.ToOrdinalWords()}");

        // Pluralization examples
        string singular = "car";
        content.Add($"Plural of 'car': {singular.Pluralize()}");
        string plural = "children";
        content.Add($"Singular of 'children': {plural.Singularize()}");

        // Byte size examples
        long bytes = 1048576;
        content.Add($"1,048,576 bytes: {bytes.Bytes().Humanize()}");

        return content;
    }
}

Humanizer C# (How It Works For Developers): Figure 11 - PDF Output

Conclusion

Humanizer is an indispensable library for .NET developers aiming to create applications that present information in a user-friendly and human-readable format. Its wide range of features, from date and time humanization to number and enum formatting, make it a versatile tool for improving the usability of applications. By leveraging Humanizer, developers can save time and effort in implementing custom formatting logic, ensuring that their applications communicate data more effectively to end-users.

Similarly, IronPDF offers comprehensive PDF generation and manipulation capabilities, making it an excellent choice for creating and handling PDF documents in C# projects. Together, Humanizer and IronPDF can significantly enhance the functionality and presentation of .NET applications. For more details on IronPDF licensing, refer to the IronPDF Licensing Information. To explore further, check out our Detailed Tutorial on HTML to PDF Conversion.

Chipego
Software Engineer
Chipego has a natural skill for listening that helps him to comprehend customer issues, and offer intelligent solutions. He joined the Iron Software team in 2023, after studying a Bachelor of Science in Information Technology. IronPDF and IronOCR are the two products Chipego has been focusing on, but his knowledge of all products is growing daily, as he finds new ways to support customers. He enjoys how collaborative life is at Iron Software, with team members from across the company bringing their varied experience to contribute to effective, innovative solutions. When Chipego is away from his desk, he can often be found enjoying a good book or playing football.
< PREVIOUS
TensorFlow .NET (How It Works For Developers)
NEXT >
OpenAPI .NET (How It Works For Developers)