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