While Creating Custom Attributes a custom class is created which is extended from ValidationAttribute Class.
public class CustomAttribute: ValidationAttribute
{
public void Test()
{
Console.WriteLine("Hello World");
}
public override bool IsValid(object? value)
{
//Logic here
if (condition)
{
return true;
}
else
return false;
}
}
Let say this custom attribute is placed above a Property of a Model.
[Custom]
public string username { get; set; }
By placing Custom over the property I am instantiating the Custom Class. Now my query is
- How & When does the IsValid() Method is Called?
- Why not the Other Methods in CustomAttribute class not called?(In this case Test() Method)
- On What basis a particular Method run in the CustomAttribute Class?
2
Answers
No, that is incorrect.
Attribute
instances are only created (and their constructors invoked) when you use theGetCustomAttributes()
methods. This is discussed here: When is a custom attribute's constructor run?Only when some validation service (which could be anything!) intentionally chooses to look for
ValidationAttribute
subclasses usingGetCustomAttributes()
and it specifically usesIsValid()
too.Because none of the code you’ve posted shows any attempt to instantiate
CustomAttribute
via reflection and call.Test()
on them.Only when the attribute is instantiated by
GetCustomAttributes()
and the consumer (the calling program) is specifically written to use the methods in[CustomAttribute]
.Your basis of understanding isn’t correct.
You are assuming what works here is an
Attribute
while you need to focus on code behavior.Attributes are "data" classes – they aren’t acting on their own.
They are useful while performing
Reflection
on classes and properties.In the DLL or EXE you could see this data in work.
Attributes help to "Mark" certain things, I advise learning more about Reflection.
To your questions:
IsValid
is called by a framework or yourself, It needs to extract theseAttribute
types specifically and callIsValid
.A good hint is the
override
keyword – means something else manages this behavior.For example let’s assume this silly attribute:
The implementing framework needs to do something like so:
I focused more on reflection because this is the key to understanding attributes.
A bit on frameworks like ASP.net:
These frameworks use extensively
Reflection
to perform many tasks and "delegate" behavior to user code.A fun experiment would be to put breakpoints on the methods you
override
and see where in the code they are called.Also check out different attributes and what they have, the basis for them is to mark certain data or behavior like the
ValidationAttribute
to perform validation on the data.Good luck!