The Piccion
The Piccion

Reputation: 35

Factory method with generics c#

I am trying to implement a factory method pattern with generics in c#. this is my code:

// IDomGen is just an empty interface that I just use as a "marker"
public abstract class AbsPersMySQL<V> where V : IDomGen
{
   ...
}

//Fascicolo is a class that implements IDomGen interface
public class PersFascMySQL : AbsPersMySQL<Fascicolo> 
{
   ...
   public static PersFascMySQL Istanza
   {
      //singleton
   }
   ...
}

//Incontro is a class that implements IDomGen interface
public class PersIncMySQL : AbsPersMySQL<Incontro> 
{
   ...
   public static PersIncMySQL Istanza
   {
      //singleton
   }
   ...
}

public class FactoryPers
{

    public static AbsPersMySQL<V> getPers<V>() where V : IDomGen
    {
        if (typeof(V) == typeof(PersFascMySQL))
        {
            return (AbsPersMySQL<V>) PersFascMySQL.Istanza;
        }

        if (typeof(V) == typeof(PersIncMySQL))
        {
            return (AbsPersMySQL<V>) PersIncMySQL.Istanza;
        }

        throw new InvalidOperationException();
    }
}

this code gives me the complier error CS0030 on the return lines of the factory method, which means that it can not convert both of the concret types into AbsPersMySQL V.

I've already read some questions about this topic and the main solution looks like to be the one using the Activator class (I haven't tried it yet, to be honest), but I foound another code snippet on this site:

public interface IReturnsValue<T>
{
    void SetValues(List<T> listOfValues);
    T NextValue { get; }
}

public class IntegerReturner : IReturnsValue<int>
{
    public void SetValues(List<int> listOfValues) { _values = listOfValues; }
    public int NextValue => _values[_indexOfNextValue++];
    private int _indexOfNextValue = 0;
    private List<int> _values = null;
}

public class DoubleReturner : IReturnsValue<double>
{
    public void SetValues(List<double> listOfValues) { _values = listOfValues; }
    public double NextValue => _values[_indexOfNextValue++];
    private int _indexOfNextValue = 0;
    private List<double> _values = null;
}

public class ValueReturnerFactory
{
    public IReturnsValue<T> CreateValueReturner<T>(string name)
    {
        if (name == "IntegerReturner")
            return (IReturnsValue<T>)new IntegerReturner();
        if (name == "DoubleReturner")
            return (IReturnsValue<T>)new DoubleReturner();
        throw  new ArgumentException();
    }
}

this code is quite similar to mine; the only difference is that this one does not give any sort of static compiler error.

Is anyone able to explain me why my code can't compile and the one I found on a site can?

Upvotes: 0

Views: 52

Answers (0)

Related Questions