Home > Blockchain >  C# generics creating new instances
C# generics creating new instances

Time:12-22

I'm attempting to write a generic method based on the following myMethod:

void myMethod(myClassA instanceA, myClassB instanceB)
{
    instanceA = new myClassA(instanceB);
}

What I've got so far is something like this (myMethod_new), which has some errors:

void myMethod_new<S, T>(S instanceA, T instanceB) where S : new()
{
    instanceA = new S(instanceB);
}

However, since I've not mastered how generics work in C#, how should this be implemented?

CodePudding user response:

You can't create a new instance of a generic type if the type has parameters in the constructor. From the docs (emphasis mine):

The new constraint specifies that a type argument in a generic class declaration must have a public parameterless constructor.

One option is to use Activator.CreateInstance and pass in the parameter(s) required. However, that can lead to runtime exceptions since the caller could pass in any type with any format of constructor.

My advice would be to refactor slightly by removing the constructor parameter and create a method to pass that value in, then use an interface to contstrain it all. For example:

// The interface
public interface IHasThing<T>
{
    void SetThing(T value);
}

// An implementation of the interface
public class Foo : IHasThing<string>
{
    private string _value;
    
    public void SetThing(string value)
    {
        _value = value;
    }
}

And your updated method that returns the new object:

public S myMethod_new<S, T>(T instanceB) where S : IHasThing<T>, new()
{
    var s = new S();
    s.SetThing(instanceB);
    return s;
}

So now you can call the method like this:

var foo = myMethod_new<Foo, string>("bar");
  • Related