class attributes in c#

1.3k views Asked by At

I need your help.

I have read about the class attributes in C# and I understood that we use them for authorization, authentication or to get some information about the class when you use reflection in the reverse process.

but really I want to understand how the attributes of authentication and authorization work and how really they can force the user to follow some restrictions when we just put the attribute above the class and we do not do any other thing, I cant understand the flow of the authentication or the authorization process using class attributes.

May be my question is not clear enough or has some mistakes but really I need some body to explain for me the authentication and the authorization process using class attributes in C#.

Clear example would be appreciated.

Thanks Every Body.

2

There are 2 answers

0
Sam I am says Reinstate Monica On BEST ANSWER

There are reflection libraries that let you get the attributes on a particular class and iterate over them.

once you understand how attribute values and properties can be iterated over with reflection then it's not too much of a stretch to conceptually understand how they can be used for validation.


You can also use reflection to iterate over methods and properties of an object, and invoke those methods/properties. Microsoft has some pretty good documentation out there for this, so if you want to look this up, you can just goggle it.


Here's a sample program. making use of attributes

class Program
{
    static void Main(string[] args)
    {
        var something = new ClassWithAttributes();
        var attributes = typeof(ClassWithAttributes).GetCustomAttributesData();

        var attribute = (SomeAttribute) Attribute.GetCustomAttribute(typeof(ClassWithAttributes), typeof (SomeAttribute));

        Console.WriteLine(attribute.Name);
        Console.ReadKey(false);
    }
}

[Some("larry")]
class ClassWithAttributes
{

}

public class SomeAttribute : System.Attribute
{
    public string Name { get; set; }

    public SomeAttribute(string name)
    {
        this.Name = name;
    }
}

and here's the documentation that I used to help me make that sample

http://msdn.microsoft.com/en-us/library/sw480ze8.aspx

http://msdn.microsoft.com/en-us/library/71s1zwct%28v=vs.110%29.aspx

0
Gigi On

Attributes apply functionality to a class by means of Reflection. The class can get the attributes it is adorned with, and use them and any parameters as needed.

Further reading: Attributes Tutorial (MSDN)