0

Default value of a deserialized List is not null when declared as public. But is null when declared as internal. Please help me in understanding why there is different default values for different access modifiers? Code below:

namespace ConsoleApplication1
{
    internal class Program
    {
        private static void Main()
        {
            DefaultTest testclass = new DefaultTest();

            var serializer = new XmlSerializer(typeof (DefaultTest));

            string path = @"C:\Users\user\Desktop\test.xml";

            var reader = new StreamReader(path);

            DefaultTest obj = (DefaultTest) serializer.Deserialize(reader);

            Console.WriteLine("[{0}]", obj.TestStr == null ? "is null" : "is not null");
        }
    }

    public class DefaultTest
    {
        public List<string> TestStr;
    }
}

This outputs "is not null". I am wondering why?

If I change TestStr to internal, it outputs "is null" correctly.

public class DefaultTest
{
    internal List<string> TestStr;
}

If I remove deserialization, then default value is null for public and internal List declarations.

namespace ConsoleApplication1
{
    internal class Program
    {
        private static void Main()
        {
            DefaultTest testclass = new DefaultTest();

            Console.WriteLine("[{0}]", testclass.TestStr == null ? "is null" : "is not null");
        }
    }

    public class DefaultTest
    {
        public List<string> TestStr;
    }
}

Outputs "is null".

test.xml has this content:

<DefaultTest>
</DefaultTest>
user1500970
  • 107
  • 1
  • 7

1 Answers1

2

Before telling you why this "strange" behavior shown here is the correct way of satisfy your serialization:

<DefaultTest>
    <TestStr>
        <string>12</string>
        <string>56</string>
        <string>2</string>
        <string>6</string>
        <string>72</string>
    </TestStr>
</DefaultTest>

Now for the null issue.

internal term from MSDN

The internal keyword is an access modifier for types and type members. Internal types or members are accessible only within files in the same assembly, as in this example:

public class BaseClass 
{
    // Only accessible within the same assembly
    internal static int x = 0;
}

For explanation why internal and Deserialization does not mix, you should check hemp ANSWER.

Community
  • 1
  • 1
Orel Eraki
  • 11,940
  • 3
  • 28
  • 36