1

I have an Interface and an Abstract class with its derived one:

  public interface IIndicator<TInput, TOutput> { } 

  public abstract class Indicator<TInput, TOutput> : IIndicator<TInput, TOutput> {

    public abstract TOutput Calculate(TInput input);

  }

  public class MyIndicator : Indicator<Decimal, Decimal?> {

    public MyIndicator(IEnumerable<Decimal> inputs) {
      // Code using base.Calculate and inputs
    }

    public MyIndicator(IEnumerable<Decimal> inputs, Func<TMapper, Decimal> mapper) {

      // Code using base.Calculate, inputs and mapper 

    } 

    public override TOutput Calculate(TInput input) {
      // Implementation of Calculate
    }

  }

The problem is that TMapper is not defined in the contructor:

public MyIndicator(IEnumerable<Decimal> inputs, Func<TMapper, Decimal> mapper, Int32 period)

I would like to use MyIndicator as:

MyIndicator indicator = new MyIndicator(inputs, x => x.Id)

Instead of:

MyIndicator<MyClass> indicator = new MyIndicator<MyClass>(inputs, x => x.Id)

Where MyClass would be something like:

public class MyClass { 
  public Int32 Id { get; set; }
}

Is this possible?

2
  • 3
    You simply need to specify MyClass instead of TMapper because there's nothing else it can be with the syntax you want. Commented Dec 10, 2019 at 19:36
  • It won't happen unless you specify a constructor argument that represent the object of the MyClass and should appear before the Mapper lambda. Commented Dec 10, 2019 at 19:59

1 Answer 1

5

Use a factory method instead e.g.

public static MyIndicator Create<TMapper>(IEnumerable<decimal> inputs, Func<TMapper, decimal> mapper, int period)
{
    var indicator = new Indicator(inputs);
    // do stuff with your mapper / period
    return indicator;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Typo I guess, but I think you meant Create<TMapper>(...).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.