0

I am trying to generate some test data using NBuilder for automation for all the classes that extends a base class wherein each class will have different fields.

Here is my code:

public interface Interface
{
    T method<T>() where T : BaseClass;
}

public class DrivedClass: BaseClass,Interface
{
    public T method<T>() where T : BaseClass
    {
        var derviedObj = Builder<DrivedClass>.CreateNew().Build();

        return derviedObj;
    }
}

return derviedObj giving error cannot implicity convert derviedObj to T

smoksnes
  • 10,509
  • 4
  • 49
  • 74
raj
  • 71
  • 7

3 Answers3

2

I'm not really familiar with nbuilder, but it looks like you could try something like this:

public class DrivedClass: BaseClass,Interface
{
    public T method<T>() where T : BaseClass
    {
        var derviedObj = Builder<T>.CreateNew().Build();

        return derviedObj;
    }
}

Or this, if that's what you're really after:

public class DrivedClass: BaseClass,Interface
{
    public T method<T>() where T : BaseClass
    {
        var derviedObj = Builder<DrivedClass>.CreateNew().Build();

        return derviedObj as T;
    }
}

Then you will get T, but there's really no chance of knowing that it will succeed. What happens when you add another implementation that doesn't inherit DrivedClass?

public class MoreDrivedClass : BaseClass, FooInterface
{

}

Then this cast will fail:

var drivedClass = new DrivedClass();
var foo = drivedClass.method<MoreDrivedClass>();

Then you will not be able to cast DrivedClass to MoreDrivedClass. Foo will be null.

smoksnes
  • 10,509
  • 4
  • 49
  • 74
1

The method can't return DerivedClass because there is no way to know if T is that class or some other one:

SomeOtherDerived v = (new DrivedClass()).method<SomeOtherDerived>(); 

It is not clear what you trying to achieve, possibly something like following sample:

public interface Interface<T> where T : BaseClass
{
    T method();
}

public class DrivedClass: BaseClass,Interface<DerivedClass>
{
  public DerivedClass method()
  {
      DerivedClass derviedObj = Builder<DrivedClass>.CreateNew().Build();
      return derviedObj ;
  }
}
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
0

Try with Activator.CreateInstance.

public class DrivedClass: BaseClass,Interface
{
  public T method<T>() where T : BaseClass
    {
      var derviedObj = Activator.CreateInstance(typeof(T));
      return (T)derviedObj ; 

    }
}


 DrivedClass drOb = new DrivedClass ();
 var v = drOb.method<desiredType_T>();
Muhammad Ashikuzzaman
  • 3,075
  • 6
  • 29
  • 53