views:

50

answers:

1

Hello, 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? Thanks.

+4  A: 

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.

Jon Skeet
You can still pass `null` in obviously, which would still allow an empty name
PostMan
I thought about constructor but as has sad PostMan, people can set null and empty what about it problem ? Also, want to use next syntax[TestProperty(Name = "Test",Value="TestValue")].
jitm
@jitm: Well, I'm afraid you can't avoid either of those problems. There's no way of preventing callers from using null, and there's no way of making it mandatory and using the property syntax. That's just the way it is, I'm afraid. You can always throw an exception if it's invalid, of course - but that could give an odd experience in some cases.
Jon Skeet
Thanks for your answer.
jitm