Boxing process of value type fields embedded in a reference type

Viewed 29

I am currently learning c#. Trying to clarify some questions regarding boxing.

Consider this example:

using System;
using System.IO;
using Newtonsoft.Json;

public sealed class Program
{

    public int value = 0;  

    public static void Main()
    {
        var p = new Program();

        var data = JsonConvert.SerializeObject(p.value);
    }

}

That is the signature of theSerializeObject method:

public static string SerializeObject(object? value)

As you can see the method I use in the example requires reference to the object as a parameter, but I am passing value type instead. I suppose that boxing must occur here. But the value field I am accessing is already allocated on a managed heap, since it is embedded field of a reference type.

The questions are:

a) Since it is obvious that local variable would get boxed in that situation (being passed as a parameter to SereializeObject()) what would happen to field access (p.value) in the example? Would the p.value be transformed into local variable and allocated on a thread stack and then get boxed?

b) What would happen if the field "value" was static? Would it get boxed?

using System;
using System.IO;
using Newtonsoft.Json;


public sealed class Program
{

    public static int value = 0;  

    public static void Main()
    {
        var p = new Program();

        var data = JsonConvert.SerializeObject(value);
    }

}
0 Answers
Related