Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# How to use interfaces

Tags:

This is a relatively straight forward question. But I was wondering what the correct usage is for accessing a method inside a separate project through the use of an interface.

Project: Test.ClassLibrary

Interface:

public interface ITest
{
    string TestMethod();
}

Class:

public class Test : ITest
{
    public string TestMethod()
    {
        return "Test";
    }
}

Project: Test.Web

Controller:

public class HomeController : Controller
{
    private ITest test;
    public ActionResult Index()
    {
        return Content(test.TestMethod());
    }

}

The above returns a NullReferenceException. I'm assuming it's because the controller gets to the interface, and doesn't know where to go next.

What's the best way to fix this? Do I have to reference the Test class in the controller or can I some how get away with only having a reference to ITest?

like image 574
mnsr Avatar asked Oct 14 '11 01:10

mnsr


People also ask

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.

What do you mean by C?

" " C is a computer programming language. That means that you can use C to create lists of instructions for a computer to follow. C is one of thousands of programming languages currently in use.

What is C language used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...


1 Answers

  • 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).

like image 68
Anthony Pegram Avatar answered Oct 01 '22 03:10

Anthony Pegram