1

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?

2
  • 1
    This code has a problem. An instance of A is passed into myMethod, and then a new one is created using new myClassA(instanceB). Can you please correct your intent? Commented Dec 22, 2021 at 11:37
  • Well, it is only an attempt, which is the problem I'm trying to solve Commented Dec 22, 2021 at 12:04

1 Answer 1

3

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");
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.