C# How to use interfaces
- You never instantiate
ITest test
, you only declare it. - Your
Test
class doesn't inherit from the interface.
You need to update your class declaration
public class Test : ITest // interface inheritance
{
And in your controller, instantiate test
.
ITest test = new Test();
As you get further along, you'll want to explore techniques for injecting the Test
instance into the controller so that you do not have a hard dependency upon it, but just on the interface ITest
. A comment mentions IoC, or Inversion of Control, but you should look into various Dependency Inversion techniques techniques (IoC is one of them, dependency injection, etc).
The class needs to read:
public class Test : ITest
in its declaration.
First off, you need to have your Test
class inherit/implement ITest
.
class Test : ITest
{
public string TestMethod() { return "test"; }
}
Then, in your controller class, you need to initialize test
-- whether directly, or in the constructor.
public class HomeController : Controller
{
public ITest test = new Test();
public ActionResult Index()
{
return Content(test.TestMethod());
}
}
Although in many cases, you should prefer to create the ITest
outside of the constructor and pass it in or something.