Saltarelle / SaltarelleCompiler

C# to JavaScript compiler – Now http://bridge.net
http://saltarelle-compiler.com
Other
297 stars 74 forks source link

[2.6.2] Casting a serializable object to its own type results in an exception when used with generics #419

Closed JechoJekov closed 9 years ago

JechoJekov commented 9 years ago

Casting a serializable object to its own type causes a "Cannot cast object to type ..." exception when the type is used with a generics method (which is often the case with LINQ's 'Cast' method).

The code below results in a "Cannot cast object to type Test.App.$SerA" exception.

[Serializable]
class SerA
{
    public int Value { get; set; }

    public SerA() { }

    public SerA(int value)
    {
        this.Value = value;
    }
}

public static class Application
{
    public static T Cast<T>(object value)
    {
        return (T)value;
    }

    public static void Main()
    {
        Console.WriteLine("Application started.");

        try
        {
            Console.WriteLine("Casting 'SerA' to 'SerA' via generics.");
            var serA = new SerA();
            Cast<SerA>(serA);
            Console.WriteLine("Success");
        }
        catch (Exception exc)
        {
            Console.WriteLine(exc.Message);
        }
    }
}
JechoJekov commented 9 years ago

Since a serializable type cannot be verified perhaps a suitable approach would be to permit casing of any serializable type to any other serializable type which by the way is already permitted when used with direct casting:

var otherObj = (OtherType)(object)myObj;

The ss.cast method can perform a check like this: if the target type is a serializable type and the object being cast is serializable then permit the casting.