1

When implementing ISerializable you write code such as this to perform custom deserialization...

(Note: this is a trivial example and does not warrant custom deserialization).

protected ClientInformation(SerializationInfo info, StreamingContext context)
{
    _culture = (string)info.GetValue("Culture", typeof(string))
}

It is required to to the GetValue method the type that you wish to deserialize, which according to the intellisense help does the following

"If the stored value cannot be converted to this type, the system will throw a System.InvalidCast exception"

Does this mean that in my example statement two casts are being performed?

Additionally, what is the point of adding this type parameter, because if I write the following

_culture = info.GetValue("Culture", typeof(string))

... this will not compile anyway as you "cannot implicitly convert type 'object' to 'string'". So this means that I must cast the object anyway and therefore if the cast is invalid I will get an InvalidCastException via my own casting in any case.

It would appear that two casts occur here and likewise in any case an error could only occur at runtime (no compile type checking which could be achieved through generics) unless anyone knows a reason why this happens?

Update: Could be that behind the scenes that an "is" operator is used to check the type is what is expected? Does "is" automatically attempt to cast?

Remotec
  • 8,966
  • 20
  • 93
  • 139
  • casts are *highly* unlikely to be the bottleneck when you're dealing with serialization - serialization generally applies to situations where some slow medium (e.g. memory, network or disk) has been involved. – Damien_The_Unbeliever Nov 29 '11 at 15:33
  • Yes, just wondered if there were more casts than required. – Remotec Nov 29 '11 at 15:40

1 Answers1

0

If we look at the implementation of GetValue it seems that the object itself is not being casted, but at least one cast occurs (Type to RuntimeType).

And some more checks that deem whether or not your object is being casted less important, as far as I can tell.

public object GetValue(string name, Type type)
{
    Type type3;
    if (type == null)
    {
        throw new ArgumentNullException("type");
    }
    RuntimeType castType = type as RuntimeType;
    if (castType == null)
    {
        throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"));
    }
    object element = this.GetElement(name, out type3);
    if (RemotingServices.IsTransparentProxy(element))
    {
        if (RemotingServices.ProxyCheckCast(RemotingServices.GetRealProxy(element), castType))
        {
            return element;
        }
    }
    else if ((object.ReferenceEquals(type3, type) || type.IsAssignableFrom(type3)) || (element == null))
    {
        return element;
    }
    return this.m_converter.Convert(element, type);
}
Bas
  • 25,270
  • 7
  • 45
  • 82