1

I am getting CS0175 Use of keyword 'base' is not valid in this context error in my unit test case project.

This is how my code looks:

A class which implements a interface

public interface iUtility
{
    void Print();
}
public class Utility: iUtility
{
    public void Print()
    {
        Console.Write("Print");
    }
}

A base class which uses the utility class and a derived class

public class BaseCls
{
    private iUtility _iUtility;
    public BaseCls()
    {
        _iUtility = new Utility();
    }

    public BaseCls(iUtility iUtility)
    {
        _iUtility = iUtility;
    }
}

public class DerivedCls : BaseCls
{
    public void PrintSomething()
    {
        Console.Write("Print Something");
    }

}

In my unit test project, I am testing derived class and trying to pass the instance of utility class. Why I am doing this may not make sense now but I am planning to use unity framework and use IoC to inject different dependencies.

I am not showing all code for brevity.

Error is happening in unit test project

[TestClass]
    public class UnitTest1
    {
        public void TestInitialize()
        {
            //I want to pass instance of utility class here
              iUtility obj = new Utility();
             DerivedCls cls = new DerivedCls(): base(obj);
        }



        [TestMethod]
        public void TestMethod1()
        {

        }
    }

What do I need to do to fix this error? I want to pass the instance of utility class from derived class through constructor.

OpenStack
  • 5,048
  • 9
  • 34
  • 69

1 Answers1

2

You need to provide a constructor in your derived class.

public class DerivedCls : BaseCls
{
    public DerivedCls(iUtility utility) : base(utility) { }

}

Then construct your DerivedCls instances as you normally would: new DerivedCls(someIUtilityInstance)

Daniel Mann
  • 57,011
  • 13
  • 100
  • 120
  • Do I need to do this even when the Derived class is not using `utility` instance? Adding this is not doing trick. I am still seeing the error. – OpenStack Feb 20 '19 at 21:07
  • @OpenStack If you need a derived class to call a specific constructor in the base class, you have to tell it which specific constructor to use by implementing a constructor in the derived class that calls the constructor in the base class; that's what my example showed. If you haven't changed the line `DerivedCls cls = new DerivedCls(): base(obj);`, that's why you're still seeing the error. – Daniel Mann Feb 20 '19 at 21:09
  • I did made the change and still seeing same issue. This is how one of the constructor in derived class looks `public DerivedCls(iUtility utility) : base(utility){}`. This is how the test case looks now. `iUtility obj = new Utility(); DerivedCls cls = new DerivedCls(obj): base(obj);` – OpenStack Feb 20 '19 at 21:14