I would like to know the approximate XML serialized size of a class instance, without actually serializing the instance. Certainly I can provide a property that explicitly sums together the size of all fields, along with padding for the XML tags that would be generated. However, (1) I'd like to know if there is already a tool that serves this purpose - perhaps an extension method and if not (2) I'd like to know how to make a loop that uses reflection to approximate the size.
Right now I'm making something like this:
private static readonly int averageTagSize = 20;
[NonSerialized]
public int EventSize
{
get
{
int size = 0;
FieldInfo[] fields = this.GetType().GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
size += averageTagSize;
switch (field.FieldType){
case typeof(int):
size += 32;
break;
case typeof(string):
string temp = field.GetValue(this) as string;
size += temp.Length;
break;
//...and so on
}
}
return 0;
}
}
The above code does not work, as the compiler will not let me switch on type info. Suggestions?