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...

CrazyEight
  • 147
  • 1
  • 18
  • 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 – Rafalon Jun 14 '23 at 08:05
  • By the way, your ternary (`?:`) logic is reversed - you currently are displaying the attribute when it is null or empty – Rafalon Jun 14 '23 at 08:10
  • You could consider using an xml serializer to convert the class to xml, and [xslt](https://www.w3schools.com/xml/xsl_intro.asp) to convert the xml to html. See [Hide Null Values](https://stackoverflow.com/questions/5818513/xml-serialization-hide-null-values) to ignore null property values. – JonasH Jun 14 '23 at 08: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? – CodeCaster Jun 14 '23 at 08: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. – Panagiotis Kanavos Jun 14 '23 at 09:02

0 Answers0