Search code examples
c#enumsextension-methods

Enum extension method can not be called


I want to elegantly create an extension method for my Enum to print the value as a string. I have written the following static extension method:

public enum Genre
{
    Action,
    Thriller,
    Comedy,
    Drama,
    Horror,
    SciFi,
}

public static class Extensions
{
    public static string StringBuilder(this Genre g)
    {
        switch (g)
        {
            case Genre.Action: return $"Action";
            case Genre.Thriller: return $"Thriller";
            case Genre.Comedy: return $"Comedy";
            case Genre.Drama: return $"Drama";
            case Genre.Horror: return $"Horror";
            case Genre.SciFi: return $"SciFi";
            default: return "";
        }
    }
}

The extension method is called in another class:

public class MovieItem
{
    public string? Title { get; }
    public int? RunningTimeMinutes { get; }
    public Enum Genre { get; }

    public MovieItem(string title, int runningTimeMinutes, Genre genre)
    {
        Title = title;
        RunningTimeMinutes = runningTimeMinutes;
        Genre = genre;
    }


    public override string ToString()
    {
        return $"Titel = {Title}, Varighed = {RunningTimeMinutes}, Genre = {Genre.StringBuilder(Genre)}";
    }
}

The problem occurs when calling the Genre.StringBuilder(Genre) producing error CS1501 "No overload for method 'StringBuilder' takes 1 arguments" - but the extension method clearly takes an argument. Have I missed something?


Solution

  • Most likely you need to change public Enum Genre { get; } to public Genre Genre { get; } And call your extension as Genre.StringBuilder()