0

In below code i can't return null, that will result in error ( T can be non-Nullable value type)

    public static T Deserialize<T>(byte[] serializedData) 
    {
        //if (serializedData == null) { return null; } //// error 

        MemoryStream memoryStream = new MemoryStream();
        BinaryFormatter binaryFormatter = new BinaryFormatter();
        memoryStream.Write(serializedData, 0, serializedData.Length);

        memoryStream.Seek(0, SeekOrigin.Begin);
        return (T)binaryFormatter.Deserialize(memoryStream);
    }

By adding default(T) will fix null issue

if (serializedData == null) { return default(T); }

but that will return default value (false for bool etc..) .. is any other way we can do this ?

Jophy job
  • 1,924
  • 2
  • 20
  • 38
  • 1
    well, what do you expect an `int` to be if there is no data? Value-types can´t be `null`. What you want is a `Nullable`, or just `int?`. – MakePeaceGreatAgain Mar 07 '19 at 07:42
  • what would be your input here? – Rahul Mar 07 '19 at 07:42
  • you can add some constraint to `T` if you need. `where T : Class` to force a reference type (thus, nullable, at least in C# 7- ) – Pac0 Mar 07 '19 at 07:43
  • @HimBromBeere for value type return Nullable , eg Nullable – Jophy job Mar 07 '19 at 07:45
  • @Pac0 but then i have to make multiple function for ref , value types etc.. – Jophy job Mar 07 '19 at 07:47
  • 3
    Then just define `T` to be `Nullable`. Your method can´t return both, a `T` and a `Nullable`. So call your method using `DeSerialize(...)`. – MakePeaceGreatAgain Mar 07 '19 at 07:47
  • you can define a flag and return that instead of null and your caller would understand that probably. – Rahul Mar 07 '19 at 07:49
  • 2
    Important bit of advice: don't use `BinaryFormatter` unless you're only using it within the context of an app-domain or IPC/RPC between two app-domains that will always be running the exact same assemblies. It is **incredibly** brittle and hates versioning. It also isn't very efficient in either CPU or data size. – Marc Gravell Mar 07 '19 at 08:03
  • What's the thinking behind creating the memory stream, writing the array to it and re-winding, rather than just passing the array to the stream's constructor? – Damien_The_Unbeliever Mar 07 '19 at 08:22
  • @MarcGravell ,@Damien_The_Unbeliever , this is existing code in old system. i can have a look on both issues . thanks for the advice – Jophy job Mar 07 '19 at 09:26

0 Answers0