Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the similarities and differences between Java Annotations and C# Attributes?

I have a Java library I'm considering porting to C#. The Java library makes extensive use of annotations (at both build time and run time.)

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?

like image 908
Jared Avatar asked Feb 16 '09 16:02

Jared


People also ask

What are the different annotations in Java?

Predefined/ Standard Annotations Four are imported from java. lang. annotation: @Retention, @Documented, @Target, and @Inherited.

Does C# have annotations?

An annotation on a program element (commonly a class, method, or field) is a piece of meta-data added to that program element which can be used to embellish that element with extra code. In Java this is called an annotation, in C# this is called an attribute.

What is an attribute C#?

Advertisements. An attribute is a declarative tag that is used to convey information to runtime about the behaviors of various elements like classes, methods, structures, enumerators, assemblies etc. in your program. You can add declarative information to a program by using an attribute.


1 Answers

Control over when your metadata is made accessible is different between the two languages.

Java provides the java.lang.annotation.Retention annotation and java.lang.annotation.RetentionPolicy enum to control when annotation metadata is accessible. The choices vary from Runtime (most common - annotation metadata retained in class files), to Source (metadata discarded by compiler). You tag your custom annotation interface with this - for example:

@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.CLASS) public @interface TraceLogging {   // etc } 

would allow you to reflect on your custom TraceLogging annotation at runtime.

C# uses the ConditionalAttribute attribute that is driven from compile time symbols. So the analogous example in C# is:

[Conditional("TRACE")] public class TraceLoggingAttribute : Attribute {   // etc } 

which would cause the compiler to spit out the metadata for your custom TraceLogging attribute only if the TRACE symbol was defined.

NB. attribute metadata is available at runtime by default in C# - this is only needed if you want to change that.

like image 133
serg10 Avatar answered Oct 02 '22 22:10

serg10