Required C # Attribute Property

I created an attribute of type

[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] [Serializable] public class TestPropertyAttribute : System.Attribute { public string Name { get { return _name; } set { _name = value; } }string _name; } 

and I should mark "Name" as a required property of this attribute. How to do it?

+4
source share
2 answers

Put it in the constructor, and not as a separate property:

 [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] [Serializable] public class TestPropertyAttribute : System.Attribute { readonly string _name; public TestPropertyAttribute(string name) { _name = name; } public string Name { get { return _name; } } } 

I do not believe that you can make this mandatory and use the Name=... syntax when applying the attribute.

+11
source

You should use the System.ComponentModel.Data.Annotations.StringLength (dot.NET 4) attribute to force the minimum string length and validate in your data. Also, (and people will mock it because it's a bad design usually *), I would throw an InvalidDataException ("You must enter a name in the attribute") from ctor when the name is not filled.

The reason I will use this is because it is a design-time attribute, and an exception is thrown when the application starts, so it would be easier to fix this for the developer, this is not the best option, but I don’t know how to contact by the designer.

I was looking for ways to directly communicate with warnings / errors in ErrorList, but so far I have not found an easy way to do this, besides creating my own custom designer or addin. I thought a lot about creating an add-on that will look for SendWarning, SendError, custom attributes, but it hasn't happened yet.

as I said

  public sealed class TestPropertyAttribute : System.Attribute { [System.ComponentModel.DataAnnotations.StringLength(50),Required] public string Name { get { return _name; } set { if (String.IsNullOrEmpty(value)) throw new InvalidDataException("Name is a madatory property, please fill it out not as null or string.Empty thanks"); } else _name= value; } string _name; } 
0
source

All Articles