Difference between different types of objects in C #

I would like to know the difference between these two Instantiation

interface ITest
{
    int TotalMarks(int englishMarks, int mathematicsMarks);
}

class TestClass : ITest
{
    public int TotalMarks(int engMarks, int mathMarks)
    {
        return engMarks + mathMarks;
    }
}

class Program
{
    static void Main(string[] args)
    {
        TestClass c = new TestClass();
        Console.Write(c.TotalMarks(10, 20));
        Console.Write("\n");

        ITest c1 = new TestClass();
        Console.Write(c1.TotalMarks(21, 34));

        Console.ReadKey();
    }
}
  • TestClass c = new TestClass();
  • ITest c1 = new TestClass();

    they work and produce the result as expected. How do these two differ and when to use that?

+4
source share
2 answers

The difference is that in the second, using the interface, you can access only those members who are present on this particular interface, and not in the entire class. This allows you to implement several different interfaces for your actual class, while only a specific “skinder” is available to the user.

In addition, an interface-oriented design is good at unit testing, as you can simply share one class with another.

, , . , , , , , . , - TestClass AnotherTestClass -instances, , . , , , . , .

. , TestClass ITest, ITest TestClass. , InvalidCastException:

ITest t = new TesClass();
AnotherTestClass t2 = (AnotherTestClass) t;

, , , , , . : Program , TotalMarks , , , . Program. , losly class-binding.

+7

,

ITest c1 = new TestClass();

, ITest, TestClass

class AnotherTestClass : ITest
{
    public int TotalMarks(int engMarks, int mathMarks)
    {
        return engMarks + mathMarks;
    }
}

 ITest c1 = new AnotherTestClass();

, TestClass c1, , , , , .

class TestClass : ITest
{
    public int TotalMarks(int engMarks, int mathMarks)
    {
        return engMarks + mathMarks;
    }
    public void AdditionalMethod()
    {

    }
}

TestClass c = new TestClass();
c.AdditionalMethod(); //Valid
ITest c1 = new TestClass();
c1.AdditionalMethod(); //Invalid, compilation error

, , .

+3

All Articles