Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Attributes mandatory property

I've created attribute like

    [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 mandatory property of this attribute. How to do it?

like image 428
jitm Avatar asked Aug 31 '10 07:08

jitm


2 Answers

Put it in the constructor instead of just 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 don't believe you can make it mandatory and use the Name=... syntax when applying the attribute though.

like image 182
Jon Skeet Avatar answered Sep 29 '22 22:09

Jon Skeet


You should use the System.ComponentModel.Data.Annotations.StringLength (dot.NET 4) attribute to force the min length of the string, and validate in your Data. Also, (and people will mock me for this as it's bad design usually*) i would throw an InvalidDataException("You must enter a Name in the attribute") from the ctor when Name is not filled.

The reason i would use this is because this is a design-time attribute and the exception would run as the app starts, so it would be easier to fix for the developer, this is not the best option, but I do not know how to communicate with the designer.

I have been looking on ways to communicate directly with the warnings/error in the ErrorList, but until now i have not found an easy way to do this, beside building my own custom designer or addin. I have thought alot about builing an addin that would look for an SendWarning, SendError , custom attributes, but have yet to make it happen.

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;
 }
like image 41
Mickey Perlstein Avatar answered Sep 29 '22 22:09

Mickey Perlstein