codiac
codiac

Reputation: 1991

C# Generic with limited return types

In C# I want to make some specialized generics that will be used just to return a specific type form another generic. The specialized generic's purpose is to force just some exact types that will be returned (like double, double[], byte, byte[]). Probably best is to explain by an example

var x = new MyGeneric<MyInterfaceDouble>();
double returnVal = x.getVal();

var x = new MyGeneric<MyInterfaceMyClass>();
MyClass returnVal = x.getVal();

So I have tried several ways to achieve this but unable to do so. Latest iteration is:

public interface IMyInterface
{}

public interface IMyInterface<T, U> :IMyInterface
{
    U getValue();
}

public class MyInterfaceDouble: IMyInterface<MyInterfaceDouble, double>, IMyInterface
{
    public double getValue()
    {
        return 8.355; 
    }
}

public class MyGeneric<T> where T : IMyInterface
{}

But I can't access the get value

var x = new MyGeneric<MyInterfaceDouble>();
double returnVal = x.getVal();   // not available

How can this be made?

Upvotes: 2

Views: 87

Answers (1)

Ali Adlavaran
Ali Adlavaran

Reputation: 3735

It seems you are going to have some changes in your design.

There is no any definiation for getVal inside IMyInterface, So is natural not available for MyGeneric<MyInterfaceDouble>.

You would inherit from IMyInterface<T, U> instead of IMyInterface:

public class MyGeneric<T> where T : IMyInterface<T, SomeSpecialType>
{}

OR

change IMyInterface defination to have getVal as general which returns object:

public interface IMyInterface
{
    object getValue();
}

OR

Change MyGeneric<T> definition to this:

public interface IMyInterface
{ }

public interface IMyInterface<T>
{
    T getVal();
}

public class MyInterfaceDouble : IMyInterface<double>, IMyInterface
{
    public double getVal()
    {
        return 8.355;
    }
}

public class MyGeneric<T> where T : IMyInterface
{
    T Obj { get; }
}

and use like this:

var x = new MyGeneric<MyInterfaceDouble>();
double returnVal = x.Obj.getVal();   // available

Also there are some other solutions which depends on your vision that you want to design.

Upvotes: 2

Related Questions