1

I was wondering if it would be possible to use a custom attribute in C# on a property that has some items.

For instance, I have a List with a default initialization of some items of type T and I want to check through an attribute if List has only unique items. I know that a List can have multiple similar objects in it, therefore you should use a HashSet to make sure only unique items exist. However, I can still declare some duplicate items in this HashSet at compile time and I would not receive any errors... (I want to receive errors before I run the program) So I was wondering if I could use something like:

[HasUniqueItemsAttribute]
public IList<string> MyCollection { get; set; } = new List<string>()
{
     "example 1",
     "example 2",
     "example 1"
};

Then I would receive an error on MyCollection that indicates that this default initialized collection does not contain unqiue items... Does anyone know how to do this?

4
  • In principle, that should work. Although it would only make sense for initialization where the collection item types are well-known. I think what you are looking for is a custom analyzer: learn.microsoft.com/en-us/dotnet/csharp/roslyn-sdk/tutorials/… But that's a lot of work to guard against something that should be easy to check yourself. Commented Nov 5, 2022 at 22:18
  • If you want to ensure uniqueness then you shouldn't be using List<T>, try HashSet<T> instead. Commented Nov 5, 2022 at 22:42
  • @Leandro your suggestion looks very interesting. I'll definitely look into it. Commented Nov 5, 2022 at 23:08
  • @DavidG You are probably right. Now that I think about it, a HashSet by default removes all duplicates. So even though I initialize a hashset with duplicate values, the hashset will remove them. I was just wondering a way for this, when using a List. Commented Nov 5, 2022 at 23:09

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.