Common Type System—Fields


Jump to: navigation, search
CSharp-Online.NET:Articles
.NET Articles

Common Type System

© 2006 Wiley Publishing Inc.

Fields

Afield is a named variable which points to a typed data slot stored on an instance of a type. Fields define the data associated with an instance. Static fields are stored per type, per application domain (roughly equivalent to a process). Field names must be unique to a single type, although further derived types can redefine field names to point at their own locations. The size of a value type value is roughly equal to the sum of the size of all of its field type sizes. (Padding can change this, that is, to ensure that instances are aligned on machine word boundaries.) Objects are similar, except that they add some amount of overhead as described above.

For example, the following type introduces a set of fields, one static and five instance:

class FieldExample
{
   private static int idCounter;
   protected int id;
   public string name;
   public int x;
   public int y;
   private System.DateTime createDate;
}

The equivalent in textual IL is:

.class private auto ansi beforefieldinit FieldExample
extends [mscorlib]System.Object
{
   .field private static int32 idCounter
   .field family int32 id
   .field public string name
   .field public int32 x
   .field public int32 y
   .field private valuetype [mscorlib]System.DateTime createDate
}

We can now store and access information in the static member from either static or instance methods, and can store and access information in the instance members in FieldExample’s instance methods.

The size of a FieldExample instance is the sum of the sizes of its fields: id (4 bytes), name (4 bytes on a 32-bit machine), x (4 bytes), y (4 bytes), and createDate (size of DateTime, which is 8 bytes). The total is 24 bytes. Notice the size of name, because it is a managed reference, will grow on a 64-bit machine; thus, the size on a 64-bit machine would be 28 bytes. And furthermore, object overhead would make the size of a FieldExample on the GC heap at least 32 bytes (on 32-bit), and likely even more.


Previous_Page_.gif Next_Page_.gif


Personal tools