2

Why do you use an attribute instead of inheriting from an interface? Wouldn’t that be easier implement an interface than adding a whole new concept to C#(attributes)?

Atribute Example:

[Serializable]
public class MyObject {
  public int n1 = 0;
  public int n2 = 0;
  public String str = null;
}

Interface Example:

public class MyObject: ISerializable {
  public byte[] getBinaryData() { // some code }
  public int n1 = 0;
  public int n2 = 0;
  public String str = null;
}
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Marcel James
  • 834
  • 11
  • 20

1 Answers1

3

Your example is not covering all functionality that attributes provide. Using interfaces you cannot express additional information about a class or a method. You will need to use attributes for it.

From MSDN

•Attributes add metadata to your program. Metadata is information about the types defined in a program. All .NET assemblies contain a specified set of metadata that describes the types and type members defined in the assembly. You can add custom attributes to specify any additional information that is required.

•You can apply one or more attributes to entire assemblies, modules, or smaller program elements such as classes and properties.

•Attributes can accept arguments in the same way as methods and properties.

•Your program can examine its own metadata or the metadata in other programs by using reflection.

Community
  • 1
  • 1
bash.d
  • 13,029
  • 3
  • 29
  • 42
  • The second bullet is an important one to emphasize - it's a *consistent* way to apply markers at all kinds of levels, rather than, say, Marker Interfaces, which could only be applied at the class/interface level. – Damien_The_Unbeliever Aug 19 '13 at 13:56