Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy does Json.NET serialization fail with [Serializable] and a lambda inside a read-only property?
    text
    copied!<p>According to <a href="http://james.newtonking.com/archive/2012/04/11/json-net-4-5-release-2-serializable-support-and-bug-fixes.aspx" rel="nofollow">these release notes</a>, Json.NET now supports the SerializableAttribute:</p> <blockquote> <p>Json.NET now detects types that have the SerializableAttribute and serializes all the fields on that type, both public and private, and ignores the properties.</p> </blockquote> <p>I have the following sample code that throws a <code>JsonSerializationException</code>:</p> <blockquote> <p>Error getting value from 'CS$&lt;>9__CachedAnonymousMethodDelegate1' on 'ConsoleApplication1.MyType'.</p> </blockquote> <p>If I comment the TotalWithLambda property, then the serialization succeeds as expected. In fact, I get the following results:</p> <ul> <li>Leave [Serializable], leave TotalWithLambda: throws JsonSerializationException</li> <li>Leave [Serializable], remove TotalWithLambda: serializes "myList" only</li> <li>Remove [Serializable], leave TotalWithLambda: serializes "myList", "Total", and "TotalWithLambda"</li> <li>Remove [Serializable], remove TotalWithLambda: serializes "myList" and "Total"</li> </ul> <p>I understand all of these cases except the first one. Why does the combination of [Serializable] and a read-only property with a lambda in it cause this exception?</p> <pre><code>namespace ConsoleApplication1 { using System; using System.Collections.Generic; using System.Linq; using Newtonsoft.Json; class Program { static void Main(string[] args) { var foo = new MyType(); foo.myList = new List&lt;int&gt;() { 0, 1, 2, 3 }; var returnVal = JsonConvert.SerializeObject(foo); Console.WriteLine("Return: " + returnVal.ToString()); Console.ReadKey(); } } [Serializable] class MyType { public IList&lt;int&gt; myList; public int Total { get { return this.myList.Sum(); } } public int TotalWithLambda { get { return this.myList.Sum(x =&gt; x); } } } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload