How can I set an initial value of a new field?

1,001 views
Skip to first unread message

Yves Goergen

unread,
Mar 14, 2014, 6:12:43 PM3/14/14
to mono-...@googlegroups.com
I'd like to create a new field in a class and it should have an initial value. I'm thinking of something like this C# code:

class MyClass
{
    public static string MyString = "The field value";
}


I have the following code right now:

var fieldDef = new FieldDefinition(
    "MyString",
    FieldAttributes.Public | FieldAttributes.Static,
    MyTypeDef.Module.Import(typeof(string)));
fieldDef.InitialValue = Encoding.Unicode.GetBytes("The field value");
MyTypeDef.Fields.Add(fieldDef);


The Unicode encoding thing is a wild guess to convert a string to a byte array. But I have no clue what to do here. The current result is that the field is created but has no value. Reading the Cecil source code in this part doesn't help me. Is there any documentation about how to use this? I haven't found any documentation about how to use anything in Cecil yet, I've come surprisingly far by just trying things out, guessing a lot and googling the rest...

Jb Evain

unread,
Mar 16, 2014, 4:23:52 AM3/16/14
to mono-...@googlegroups.com
Hi Yves,

The InitialValue is a particular beast for primitive types.

I encourage you to look at the IL created for your C# code in ildasm,
you'll get a class constructor initializing the field with a string,
like this:

MyClass::.cctor
{
ldstr "The Field Value"
stsfld MyClass.MyString
}

You just need to recreate this.

Jb
> --
> --
> --
> mono-cecil
> ---
> You received this message because you are subscribed to the Google Groups
> "mono-cecil" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to mono-cecil+...@googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.

Yves Goergen

unread,
Mar 16, 2014, 6:07:41 AM3/16/14
to mono-...@googlegroups.com
Am Sonntag, 16. März 2014 09:23:52 UTC+1 schrieb Jb Evain:
I encourage you to look at the IL created for your C# code in ildasm,
you'll get a class constructor initializing the field with a string,
like this:

Alright, I see. I've seen constant strings have their value set directly with the field so I thought it would be the same for non-constant fields, but that doesn't seem to be the case for strings and ints. They're all set in the instance constructor.
Reply all
Reply to author
Forward
0 new messages