Anton Petrov
Anton Petrov

Reputation: 43

How to implement something like this in C#: var provider = options.IsBinary ? new BinaryProvider() : new NonBinaryProvider()

It is possible to implement in C# something like this:

var provider = options.isBinary ? new BinaryProvider() : new NonBinaryProvider()

Both BinaryProvider and NonBinaryProvider implement IProvider<T>.

public interface IProvider<out T>
{
    T GetValue(string traceId);
    T GetValue(ulong sessionId);
}

Upvotes: 3

Views: 60

Answers (2)

Michał Turczyn
Michał Turczyn

Reputation: 37460

It's not possible, since compiler will not know what you mean by var - is it BinaryProvider and you made a mistake by trying to pass also NonBinaryProvider? Or is it the other way around? Or should it infer base type for both classes? If they have more than one common base type - which one to infer?

There is a lot of ambiguity in this situation. You need to help the compiler and hint what type you would like to use. Most probably they both implement IProvider with the same generic parameter.

So as a first step I would do (assuming generic parameter is long):

IProvider<long> p = true ? new BinaryProvider() : new NonBinaryProvider();

And if you want to preserve using var (I like it too :) ), you can specify helper method, which will decaclare the IProvider<long> as return type:

public static void Main()
{
    var p = GetProvider(true);
}

public static IProvider<long> GetProvider(bool condition) =>
    condition ? new BinaryProvider() : new NonBinaryProvider();

Upvotes: 0

Mike Christensen
Mike Christensen

Reputation: 91686

Both BinaryProvider and NonBinaryProvider would need an implicit conversion to the same base type, which would also need to be specified on the declaration of provider. Therefore, we can't really answer your question as stated since we don't know exactly what implementation of IProvider<T> both classes implement. Assuming it's the same, what you'd want is:

using System;

class Program
{
    static void Main() {
        int x = 10;
        IProvider<double> provider = x < 20 ? new BinaryProvider() : new NonBinaryProvider();
    }
}

public interface IProvider<out T>
{
    T GetValue(string traceId);

    T GetValue(ulong sessionId);
}

class BinaryProvider : IProvider<double>
{
    public double GetValue(string traceId) => 1D;
    public double GetValue(ulong sessionId) => 1D;
}

class NonBinaryProvider : IProvider<double>
{
    public double GetValue(string traceId) => 0D;
    public double GetValue(ulong sessionId) => 0D;
}

Upvotes: 3

Related Questions