Skip to content

Instantly share code, notes, and snippets.

@ianfnelson
Created March 29, 2014 20:14
Show Gist options
  • Save ianfnelson/9862098 to your computer and use it in GitHub Desktop.
Save ianfnelson/9862098 to your computer and use it in GitHub Desktop.
Snippets for 2006 blog post "A Serializable KeyValuePair Class"
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace IanFNelson
{
[Serializable()]
public class KeyValuePairCollection<TKey, TValue> :
Collection<KeyValuePairThatSerializesProperly<TKey, TValue>>
{
public void Add(TKey key, TValue value)
{
this.Add(new KeyValuePairThatSerializesProperly<TKey,
TValue>(key, value));
}
}
}
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace IanFNelson
{
[Serializable()]
public class KeyValuePairKeyedCollection<TKey, TValue> :
KeyedCollection<TKey, KeyValuePairThatSerializesProperly
<TKey, TValue>>
{
protected override TKey GetKeyForItem(
KeyValuePairThatSerializesProperly<TKey, TValue> item)
{
return item.Key;
}
public void Add(TKey key, TValue value)
{
this.Add(new KeyValuePairThatSerializesProperly<TKey,
TValue>(key, value));
}
}
}
using System;
using System.Runtime.InteropServices;
using System.Text;
namespace IanFNelson
{
/// <summary>
/// It's just like a System.Collections.Generic.KeyValuePair,
/// but the XmlSerializer will serialize the
/// Key and Value properties!
/// </summary>
[Serializable, StructLayout(LayoutKind.Sequential)]
public struct KeyValuePairThatSerializesProperly<TKey, TValue>
{
private TKey key;
private TValue value;
public KeyValuePairThatSerializesProperly(TKey key, TValue value)
{
this.key = key;
this.value = value;
}
public override string ToString()
{
StringBuilder builder1 = new StringBuilder();
builder1.Append('[');
if (this.Key != null)
{
builder1.Append(this.Key.ToString());
}
builder1.Append(",");
if (this.Value != null)
{
builder1.Append(this.Value.ToString());
}
builder1.Append(']');
return builder1.ToString();
}
/// <summary>
/// Gets the Value in the Key/Value Pair
/// </summary>
public TValue Value
{
get { return this.value; }
set { throw new NotSupportedException(); }
}
/// <summary>
/// Gets the Key in the Key/Value pair
/// </summary>
public TKey Key
{
get { return this.key; }
set { throw new NotSupportedException(); }
}
}
}
using System;
using System.Collections.ObjectModel;
using System.Collections;
using System.Collections.Generic;
namespace IanFNelson
{
[Serializable()]
public class ReadOnlyKeyValuePairCollection<TKey, TValue> :
ReadOnlyCollection<KeyValuePairThatSerializesProperly<TKey, TValue>>
{
public ReadOnlyKeyValuePairCollection(
IList<KeyValuePairThatSerializesProperly
<TKey, TValue>> list) :
base(list) { }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment