Search code examples
c#streamusing

Using using in a constructor


I am using a create method for a constructor of a converter.

public void loadData()
{
    byte [] data = new byte [] {......}; // some byte data in here
    var converter = GetDataConverter(data);
}

Now inside the GetDataConverter I need to create a memorystream from the binary data (the converter is 3rd party and takes a stream) If I write the GetDataConverter like this I get an error telling me I didnt' dispose which I understand. I created a MemoryStream and I need to dispose.

public MyDataConverter GetDataConverter(byte [] data)
{
    return new MyDataConverter(new MemoryStream(data));
}

So my solution would be this:

public MyDataConverter GetDataConverter(byte [] data)
{
    using(var ms = new MemoryStream(data))
    {
       return new MyDataConverter(ms);
    }
}

The question is, is my solution correct? Should I be using a 'using' here? isn't the 'using' going to destroy my memory stream once it's out of scope so the converter will have nothing to work on?

I need an answer AND an explanation please, I'm a bit vague on the whole 'using' thing here.

Thanks


Solution

  • If you have no access to the code of ´MyDataConverter´ and the type doesn't implements ´IDisposable´ you can do:

    public void loadData()
    {
        byte[] data = new byte[] { 0 }; // some byte data in here
    
        using (var stream = new MemoryStream(data))
        {
            var converter = new MyDataConverter(stream);
    
            // do work here...
        }
    }
    

    If you have to use this many times and want to reuse your code you can do something like this:

    public void loadData()
    {
        byte[] data = new byte[] { 0 }; // some byte data in here
    
        UsingConverter(data, x =>
        {
            // do work here...
        });
    }
    
    void UsingConverter(byte[] data, Action<MyDataConverter> action)
    {
        using (var stream = new MemoryStream(data))
        {
            var converter = new MyDataConverter(stream);
    
            action(converter);
        }
    }