home comics writing pictures archive about

2023-11-05 - In IL: Field Definitions

In IL

Fields are used to store information as part of a type.

.field <attributes…> <type> <Id> <initializer>

A field is declared using the .field directive. This is followed by a set of attributes which describe how the field behaves. The type indicates what kind of data the field contains, Id is the name of the field, and the initializer is used to set the value of the field

There are a variety of attributes that can be set.

Accessibility

The accessibility attributes are used to indicate where the field can be accessed.

Attribute Description
private Visible only within the containing class
famandassem Visible to containing class and derived classes within the same assembly
assembly Visible to the containing assembly
family Visibility to containing class and derived classes
famorassem Visibility to containing class and derived classes or to the containing assembly
public Visible everywhere

Contract Attributes

The contract attributes are used to control how the field can be used

Attribute Description
static Indicates that the field is associated with the type. Not specifying static means that the field is specific to each instance
initonly Indicates that the field can only be modified in a constructor
literal (static only) indicates that the field can only have the value specified as part of its declaration

Interoperation Attributes

The marshal (<NativeType>) attribute is used to specify how this field should be handled during marshalling

Special attributes

These attributes are used to indicate that the field should be treated in a special way

Attribute Description
rtspecialname The field has a special meaning to the runtime
specialname The field has a special meaning to something besides the runtime

Type

We saw examples of types when we looked at variables. User defined value types start with valuetype and reference types start with class. This is followed by the fully qualified name of the type including namespaces and the source assembly. Built-in types use the simple name of the type and value or reference type is implied.

Initialization

initialization is specified using an equal sign followed by <type>(<value>) where type is one of the built-in types and value is the value to initialize the variable with.

Next time we will look at some examples.

Comments: