Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Attributes and Metadata implication

I read tutorials from the web about C# Attributes and Metadata. It's very cool but I'm wondering its implication.

  1. Are (custom) attributes loaded when the assembly is loaded? or is it only when you use reflection to retrieve the metadata?

  2. It seems the attributes add to the total of code size because it gets compiled in to the executable? Is this right?

  3. Is it possible to have compile time attributes? I.e. attributes will only be applied if DEBUG is defined?

I know one is to do like this:

#if DEBUG
[MyCustomAttribute]
#endif

But I wonder if there's better way?

  1. Is there any performance/memory caveat when using a lot of attributes? My target platform will be Xbox 360 (using C#/XNA).

Thanks!

-Stephanus

like image 344
tep Avatar asked Mar 24 '10 15:03

tep


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.

Is C language easy?

Compared to other languages—like Java, PHP, or C#—C is a relatively simple language to learn for anyone just starting to learn computer programming because of its limited number of keywords.

Is C programming hard?

C is more difficult to learn than JavaScript, but it's a valuable skill to have because most programming languages are actually implemented in C. This is because C is a “machine-level” language. So learning it will teach you how a computer works and will actually make learning new languages in the future easier.


1 Answers

There are two parts to attributes, their code and their constructor argument and property data. The code is stored in the IL of the assembly, the data is stored in the assembly metadata. If an attribute isn't used, that only takes up some virtual memory space but doesn't require any machine resources.

Nothing happens until you use the GetCustomAttributes() method. Then the code for the attribute class gets just-in-time compiled, just like the regular code in your assembly. And the constructor and the property setters are called, using the attribute data in the metadata. You'll use up some RAM for both when the memory manager maps the IL, machine code and the metadata pages.

like image 62
Hans Passant Avatar answered Oct 01 '22 02:10

Hans Passant