Click here to Skip to main content
15,892,005 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Hello Folks,

I am new using codeDom and after some tutorials I was able to build interesting things. However I am facing a limitation regarding how to set custom attributes declaration for a method. e.g.

[PexMethod (Max Branches = 1000)]
public void myMethod()
....

I am able to declare just [PexMethod()], but I am not able to set the "Max Branches..". My intention is to build parameterized unit tests and then let Pex explore my custom PUT method.
If someone could please give a hint I will really appreciate it.

Thanks in advance.

Pedro
Posted
Comments
Sergey Alexandrovich Kryukov 30-Apr-12 17:51pm    
How come it's turned out to be a problem? Just use valid .NET identifier, like MaxBranches.
--SA
satrio_budidharmawan 30-Apr-12 23:29pm    
Yes, agree wit --SA.
How come you change the way .Net works...declaring something with with_white_space..
petBorromeo 1-May-12 8:57am    
Yep, it was a mistake by writting the declaration. However the solution provided by SA has solve my problem. Thanks for your help guys!

1 solution

Attributes are powerful, useful, but very limited in several aspects. But — rejoice! — not that limited as you might think. They still allow some good set of parameter types:
http://msdn.microsoft.com/en-us/library/ms177221%28v=vs.100%29.aspx[^].

This is how it may look in your case:
C#
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
class PexMethodAttribute : System.Attribute {
    public int MaxBranches { internal get; set; }
}


Pay attention for internal. You can check the attribute valued only in the same assembly where it is declared, which is pretty reasonable. Most likely, you will need to have the setter set public, because you set it in the code applying the attribute.

Here is how you can apply your attribute type to some method:

C#
[PexMethod(MaxBranches = 1000)]
void SomeMethod(/* ... */) {/* ... */}


Alternatively, you can use constructor syntax for the parameter:

C#
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
class PexMethodAttribute : System.Attribute {
    internal int MaxBranches { get; set; }
    public PexMethodAttribute(int maxBranches) { this.MaxBranches = maxBranches; }
}


And the application of it would look a bit different:
C#
[PexMethod(1010)]
void SomeMethod(/* ... */) {/* ... */}


—SA
 
Share this answer
 
v5
Comments
Sandeep Mewara 1-May-12 3:30am    
My 5+ !
petBorromeo 1-May-12 8:58am    
Thank you very much SA, your quick answer has help me a lot.!!
Sergey Alexandrovich Kryukov 1-May-12 10:53am    
You are very welcome.
Good luck, call again.
--SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900