0

I have a C# .NET 6 class that looks like the following

public class HtmlElement
{
    public string Prop1 { get; set; }
    public string Prop2 { get; set; }
    public string Prop3 { get; set; }

    public override string ToString() => $@"<htmlElement" 
        + (string.IsNullOrEmpty(Prop1) ? $@" prop1=""{Prop1}""" : string.Empty)
        + (string.IsNullOrEmpty(Prop2) ? $@" prop2=""{Prop2}""" : string.Empty)
        + (string.IsNullOrEmpty(Prop3) ? $@" prop3=""{Prop3}""" : string.Empty)
        + "></htmlElement>"
    ;
}

Is there a more elegant way to get the desired output when calling ToString() so that every property of the class HtmlElement only becomes an attribute when its not null or empty?

I was thinking of something like annotations on the class properties or something...

5
  • You could maybe start by creating a function (say DisplayProp) that will take care of the null check, so you don't have to repeat this for each property Commented Jun 14, 2023 at 8:05
  • By the way, your ternary (?:) logic is reversed - you currently are displaying the attribute when it is null or empty Commented Jun 14, 2023 at 8:10
  • You could consider using an xml serializer to convert the class to xml, and xslt to convert the xml to html. See Hide Null Values to ignore null property values. Commented Jun 14, 2023 at 8:17
  • Why do you want to create your own HTML element? Can't you use a TagHelper or is this a contrived example and/or aren't you in an ASP.NET Core environment? Commented Jun 14, 2023 at 8:23
  • 1
    Why should ToString() generate HTML in the first place? That's the job of an HTML renderer or template engine, like Razor or Scriban. Generating temporary strings is expensive, both in allocations and garbage collection, which is why renderers write directly to a stream instead of concatenating strings. Commented Jun 14, 2023 at 9:02

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.