Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You will need to add some kind of flag to let the reader know if it should read the next bytes or not.</p> <pre><code>public decimal? ReadNullableDecimal() { bool hasValue = ReadBoolean(); if (hasValue) return ReadDecimal(); return null; } public void Write(decimal? val) { bool hasValue = val.HasValue; Write(hasValue) if(hasValue) Write(val.Value); } </code></pre> <p>However we can be clever and create a generic method that works for all struct based types</p> <pre><code>public Nullable&lt;T&gt; ReadNullable&lt;T&gt;(Func&lt;T&gt; ReadDelegate) where T : struct { bool hasValue = ReadBoolean(); if (hasValue) return ReadDelegate(); return null; } public void Write&lt;T&gt;(Nullable&lt;T&gt; val) where T : struct { bool hasValue = val.HasValue; Write(hasValue) if(hasValue) Write(val.Value); } </code></pre> <p>If I wanted to use my <code>ReadNullable</code> function to read a <code>Int32</code> I would call it like</p> <pre><code>Int32? nullableInt = customBinaryReader.ReadNullable(customBinaryReader.ReadInt32); </code></pre> <p>So it would test if the value exists, then if it does it would then call the passed in function.</p> <hr> <p><strong>EDIT:</strong> After sleeping on it, the <code>Write&lt;T&gt;</code> method may not work like you expect it to. Because <code>T</code> is not a well defined type the only method that could support it would be <code>Write(object)</code> which Binary writer does not support out of the box. <code>ReadNullable&lt;T&gt;</code> will still work, and if you want to use still use <code>Write&lt;T&gt;</code> you will need to make the result of <code>val.Value</code> <a href="http://msdn.microsoft.com/en-us/library/vstudio/dd264741.aspx" rel="nofollow">dynamic</a>. You will need to benchmark to see if there are any performance issues with this.</p> <pre><code>public void Write&lt;T&gt;(Nullable&lt;T&gt; val) where T : struct { bool hasValue = val.HasValue; Write(hasValue) if(hasValue) Write((dynamic)val.Value); } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

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