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

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)