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 these Attribute
types specifically and call IsValid
.
A good hint is the override
keyword - means something else manages this behavior.
- While this is possible - to extract by reflection all of public methods and invoke them, frameworks aren't designed to call custom public methods because it's unsafe, unexpected and generally not recommended.
- On framework basis - if a framework was designed to call these methods then they would call them, else it simply wouldn't care what methods you define.
For example let's assume this silly attribute:
public class MyAttrib : ValidationAttribute
{
public MyAttrib()
{
Console.WriteLine("Hello from attrib ctor");
}
public override bool IsValid(object? value)
{
if (value == null) return false;
if (value != null && value.GetType() != typeof(string))
{
return false;
}
string? s = value as string;
return s == "Hello World";
}
}
[MyAttrib]
public class A
{
}
The implementing framework needs to do something like so:
var assm = Assembly.GetExecutingAssembly();
foreach (var type in assm.GetTypes())
{
if (type.IsAssignableFrom(typeof(A)))
{
Console.WriteLine($"Found type {type}");
var attributeType = type.GetCustomAttribute<MyAttrib>();
var isValid = attributeType.IsValid("Hello World");
Console.WriteLine($"Is Valid? {isValid}");
}
}
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!