Search code examples
c#memorystreamexpandable

How to determine if MemoryStream is fixed size?


My method gets MemoryStream as parameter. How can I know whether this MemoryStream is expandable?

MemoryStream can be created using an array using "new MemoryStream(byte[] buf)". This means that stream will have fixed size. You can't append data to it. On other hand, stream can be created with no parameters using "new MemoryStream()". In this case you can append data to it.

Question: How can I know - can I safely append data in a current stream or I must create a new expandable stream and copy data to it?


Solution

  • You can do that using reflection:

    static bool IsExpandable(MemoryStream stream)
    {
        return (bool)typeof(MemoryStream)
            .GetField("_expandable", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)
            .GetValue(stream);
    }
    

    I don't know if there's a cleaner/safer way to retrieve this information.