Adam
Adam

Reputation: 65

Class / constructor to Action<T>?

I have two classes and they both inherit from Stream class.

FirstClass : Stream 
{
    FirstClass(Stream, CompressionMode) 
    {
         ..
    } 
}

SecondClass : Stream 
{
    SecondClass(Stream, CompressionMode) 
    {
         ..
    } 
}

I want to put one of these classes to a variable (Action i guess) and then make a new object from that variable – like this:

Action<Stream, CompressionMode> classPattern = condition ? FirstClass : SecondClass

///And now this
var newObject = classPattern(Stream, CompressionMode);

///Or maybe even this
classPattern newObject = classPattern(Stream, CompressionMode);

How do you that?

Thanks for help <3

Upvotes: 1

Views: 102

Answers (2)

Pavel Anikhouski
Pavel Anikhouski

Reputation: 23218

It seems, that you'll need a Func delegate with two parameters

Func<Stream, CompressionMode, Stream> classPattern = (stream, mode) => condition ? (Stream)new FirstClass(stream, mode) : new SecondClass(stream, mode);

and use it

var newObject = classPattern(stream, compressionMode);

You may also convert it to a local function

Stream ClassPattern(Stream stream, CompressionMode mode) =>
    condition ? (Stream) new FirstClass(stream, mode) : new SecondClass(stream, mode);

Upvotes: 2

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

I doubt if you really want any lambda (Func<Stream, CompressionMode, Stream>) here. If you have many modes, conditions, options, labda will be too complex to maintain. I suggest factory class:

public static class MyClassBuilder {
  public static Stream Create(Stream parent, CompressionMode mode) {
    // Note, that we can easily include validation into factory's method  
    if (null == parent)
      throw new ArgumentNullException(nameof(parent));

    return condition(mode, parent)  
      ? new FirstClass(parent, mode)
      : new SecondClass(parent, mode);
  }

  // It's easy to implement building with default mode:
  public static Stream Create(Stream parent, CompressionMode mode) =>
    Create(parent, CompressionMode.MaximumCompression);  
}

....

var newObject = MyClassBuilder.Create(someStream, someCompressionMode);

// with default CompressionMode
var otherObject = MyClassBuilder.Create(someOtherStream);

Upvotes: 2

Related Questions