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...
DisplayProp) that will take care of the null check, so you don't have to repeat this for each property?:) logic is reversed - you currently are displaying the attribute when it is null or emptyToString()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.