Skip to content

ImageFormatManager.TryFindFormatByFileExtension throws when null or whitespace is bad practice #2385

@bjkippax

Description

@bjkippax

Prerequisites

  • I have written a descriptive issue title
  • I have verified that I am running the latest version of ImageSharp
  • I have verified if the problem exist in both DEBUG and RELEASE mode
  • I have searched open and closed issues to ensure it has not already been reported

ImageSharp version

3.0.0

Other ImageSharp packages and versions

n/a

Environment (Operating system, version and so on)

Windows 10 & 11, 64bit, build 22000.1574

.NET Framework version

.NET 7

Description

The "ImageFormatManager.TryFindFormatByFileExtension" method here throws, which is against the TryX pattern.

public bool TryFindFormatByFileExtension(string extension, [NotNullWhen(true)] out IImageFormat? format)
    {
        Guard.NotNullOrWhiteSpace(extension, nameof(extension));

        if (extension[0] == '.')
        {
            extension = extension[1..];
        }

        format = this.imageFormats.FirstOrDefault(x =>
            x.FileExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase));

        return format is not null;
    }

What you'd expect is that methods beginning with TryXXXX would never throw and instead simply return false.
Crude example but;

public bool TryFindFormatByFileExtension(string extension, [NotNullWhen(true)] out IImageFormat? format)
{
    try
    {
        Guard.NotNullOrWhiteSpace(extension, nameof(extension));

        if (extension[0] == '.')
        {
            extension = extension[1..];
        }

        format = this.imageFormats.FirstOrDefault(x =>
            x.FileExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase));
    catch (Exception)
    {
        // Do nothing
    }

    return format is not null;
}

It should be the responsibility of the consuming application to ensure that it has thoroughly tested its implementation of this method.

Steps to Reproduce

// this
ImageFormatManager.TryFindFormatByFileExtension("", out ImageFormat? foo);

// or this
ImageFormatManager.TryFindFormatByFileExtension(null, out ImageFormat? foo);

Images

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions