Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Annotations in dotnet

I've never used C# attributes, but understand that they are the rough equivalent of Java annotations.

If I proceed with the port using attributes to replace annotations, what do I need to know? What's going to be the same? Different? What's going to bite me?

As for as my research i found that

C# uses the ConditionalAttribute attribute that is driven from compile time symbols

i just want to know whether can we write annotation on our own and which versions of dotnet supports it?

It is appreciated that if i got any samples or documents to read

Waiting for your valuable response and comments


1 Answers

Yes, you can write your own attributes - you just inherit from Attribute, i.e.

public class FooAttribute : Attribute {
    public int Bar {get;set;}
}

then you can attach that:

[Foo(Bar=12)]
public int X {get;set;}

(see also AttributeUsageAttribute if you want to limit what it can be applied to - for example to classes, fields, interfaces, etc)

Note that while some attributes (ConditionalAttribute, ObsoleteAttribute, etc) have meaning to the compiler, you cannot write your own compile-time features with attributes, except via 3rd-party tools such as PostSharp. What you can do is check for the attribute at runtime via reflection (in particular, Attribute.GetCustomAttribute[s]), and react accordingly with code. Most attributes are used in this way by reflection.

foreach(var prop in type.GetProperties()) {
    var foo = (FooAttribute)Attribute.GetCustomAttribute(
                        prop, typeof(FooAttribute));
    if(foo != null) {
        Console.WriteLine("{0} has Foo.Bar: {1}", prop.Name, foo.Bar);
    }
}

All versions of .NET support attributes, although in some of the limited frameworks you might find some of the BCL attributes are missing if not required. For example, DataContractAttribute doesn't exist on a platform that doesn't support WCF via DataContractSerializer.

like image 128
Marc Gravell Avatar answered Dec 10 '25 02:12

Marc Gravell