7

Right now, without using properties, I've got this:

public void SetNumber([Array(new int[]{8})] Byte[] number)

As you can see, I am adding the ArrayAttribute attribute to the parameter.

What I want to do is the same but on a property setter. This doesn't work:

[Array(new int[]{8})]
public Byte[] SetNumber
{
  set
  {
  }
  get
  {
    return null;
  }
}

Is there any way of attaching the attribute to the set_SetNumber value method parameter?

Also, a related question. The two methods generated (the get/set) don't have the custom attribute. Can anyone explain to me why is that?

3 Answers 3

9

You need to use the param attribute target on the set:

public Byte[] SetNumber {
  [param: Array(new int[] { 8 })]
  set {
  }
  get {
    return null;
  }
} 

As for the second question, the custom attribute is set on the property itself, not on the property accessor methods.

Also, if your ArrayAttribute only ever applies to parameters, it could be defined like this:

[AttributeUsage(AttributeTargets.Parameter)]
public class ArrayAttribute : Attribute {
  // ...
}
Sign up to request clarification or add additional context in comments.

Comments

0

I'm not certain, but my guess is that you can't do what you want - the setter value parameter isn't exposed for you to apply an attribute to.

And as for your second question, a property is distinct from it's getter & setter methods. You can apply an attribute to the setter method like so:

public Byte[] SetNumber
{
  [Array(new int[]{8})]
  set
  {
  }
  get
  {
    return null;
  }
}

1 Comment

I tried that, but I still get null when I try to invoke GetCustomAttribute(true) on the set method version of the Property (in Debug Immediate window). Anyway I think I will give up on the idea for now. Thanks.
-1

You dont do that, create a method just as you have done in the first example. You cant pass anything other than value to the set.

public Byte[] TheNumber
{
    private set;
    get
    {
        return null;
    }
}

public void SetNumber([Array(new int[] { 8 })] Byte[] number)
{
    this.TheNumber = number;
}

2 Comments

BTW, if you have an exposed property like above, you can use private set;
Actually, that might work. Just a bit of background note, I am generating these methods from a XML file. The attribute is for the unit test to generate a proper length array as the parameter.

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.