Trying to learn about attributes - can someone explain this simple one and why it doesnt work?
code is pretty self explanatory, why when I set a debug point in the attribute it wont stop? in addition it prints altho the value is 1 and not 0
21 Replies
I mean first of all attributes are purely metadata. They don't do anything on their own
But also, 1 != 0
So i don't know what you expect it to do
I mean, isnt there an [authorize] attribute that checks for auth?
Which does a bunch of stuff because it was implemented by another class to do a bunch of stuff
so it can be done no? lets say i wanted to do something like this whats the way?
You need to check for the attribute's existence using things like reflection
No clue, someone else has to answer that
I never use attributes
well feel free to tag one of the c# gods, thanks for explaning a bit mate
@Orannis
That doesn't work like you seem to think it does
It doesn't change your method
The caller of your method looks for that attribute and enables authorization if it's there
but it does prevent the method from being executed if im not authorized, lets say i wanted to accomplish the same thing if the integer is 0 and not 1
how would i go about that?
lets say something simpler
an attribute that prevents a methode from doing a cw
if it returns false
Because the caller of your method looks for that attribute
You'd need to do the same
Ie, where you call this method, look for that attribute
can u show me a short example?
No short examples exist
Just make a simple helper method to throw when out of range, don't use attributes
I know there are other ways, trying to learn about attributes becuse sometimes i see these monster foot long attributes being used in code
and im cluelss as to how they work
What we're discussing here is a pattern of coding called Aspect-Oriented (AOP). C# doesn't really support that
Attributes are purely metadata
That's it
They're tags
When does an attribute's ctor get ran?
Buy they [Authorize] One has meaning, even if the caller function looks for it
some logic does happen
some code is being invoked
Because the caller looks at that metadata
Like when you're searching on an online store, and you use a filter
You looked for a tag, read the data it had, and selected it
And then everything that didn't have the tag was filtered out
Same deal with attributes
I see, good explanation, but just to clarify
if i call a method that has the auth attribute, the invoker does a meta data check to see if that user lets say is singed in, and if he's not and it returns like a false boolean, the method doesnt get invoked at all
Yup
I see, great stuff, thanks mate have a good evening !
The caller uses reflection to get that info
You too