0

in this simple class I try to overwrite ToString() to show all custom Attributes.

public class TryMe
{
    public TryMe(int id, List<String> tests)
    {
        ID = id;
        Tests = tests;
    }
    public int ID { get; set; }
    public List<String> Tests { get; set; }

    public override string ToString()
    {
        string me = "";
        var attributes = this.GetType().GetCustomAttributes();

        foreach (var attribute in attributes)
        {
            me = me + attribute.ToString() + ",";
        }
        return me;
    }
}

It doesn't show any value or error.

Aren't ID and Tests custom attributes ? Is there any easy enumeration if the class becomes bigger ?

DV82XL
  • 5,350
  • 5
  • 30
  • 59
user3732793
  • 1,699
  • 4
  • 24
  • 53
  • You should also use a StringBuilder in this case, much more efficient! – jason.kaisersmith Aug 19 '21 at 08:20
  • https://stackoverflow.com/questions/2762531/c-sharp-reflection-and-getting-properties – TheGeneral Aug 19 '21 at 08:22
  • https://stackoverflow.com/questions/737151/how-to-get-the-list-of-properties-of-a-class – TheGeneral Aug 19 '21 at 08:23
  • https://learn.microsoft.com/en-us/dotnet/api/system.type.getproperties?view=net-5.0 – TheGeneral Aug 19 '21 at 08:24
  • [Attribute](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/attributes/) are not [Properties](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/properties) – DavidG Aug 19 '21 at 08:25
  • 1
    @jason.kaisersmith In this case a `StringBuilder` would almost certainly be slower. It tends to be better when you make 6 or 7 string operations so you'd need more properties. Of course, YMMV and testing is always useful when perf is a concern. – DavidG Aug 19 '21 at 08:27
  • `return string.Join(", ", this.GetType().GetProperties().Select(x => x.Name))` – TheGeneral Aug 19 '21 at 08:29
  • @DavidG OK, I thought the benefit was already with 3 or 4, good to know, thanks. But remember that most people post a simplified Class on SO not the full one, and with the starting empty string and comma then you already have 5 strings being concatenated in this case. – jason.kaisersmith Aug 19 '21 at 08:46
  • @TheGeneral Thanks for your replies. Actually the solution from fso did work quite well as I had to iterate over the properties to get name and value back. Where I am struggle is getting the value of the tests list back as string. – user3732793 Aug 19 '21 at 11:48
  • @jason.kaisersmith could not answer to repliers at once on Stackoverflow. – user3732793 Aug 19 '21 at 11:49

1 Answers1

5

Attributes are things like there:

[MyCoolAttribute]
public MyCoolMethod()

What you're looking for are Properties

this.GetType().GetProperties()

faso
  • 679
  • 7
  • 25