sam
sam

Reputation: 149

How to call an interface in C#

interface ISample
{
    int fncAdd();
}

class ibaseclass
{
    public int intF = 0, intS = 0;
    int Add()
    {
        return intF + intS;
    }
}
class iChild : ibaseclass, ISample
{
    int fncAdd()
    {
        int intTot = 0;
        ibaseclass obj = new ibaseclass();
        intTot = obj.intF;
        return intTot;
    }
}

I want to call ISample in static void Main(string[] args) but I dont know how to do that. Could you please tell me how?

Upvotes: 3

Views: 34004

Answers (3)

Venemo
Venemo

Reputation: 19067

An interface cannot be instantiated by itself. You can't just call an interface. You need to instantiate a class that actually implements the interface.

Interfaces don't and can't do anything by themselves.

For example:

ISample instance = new iChild(); // iChild implements ISample
instance.fncAdd();

The following questions provide more detailed answers about this:

Upvotes: 10

MattC
MattC

Reputation: 4004

Do you mean?:

static void Main(string[] args)
{
    ISample child = new iChild();
    child.fncAdd();
}

Although, as stated by others the code doesn't seem like it's using inheritance correctly.

Upvotes: 2

Shadow Wizard
Shadow Wizard

Reputation: 66389

You can't "call" interface or create instance of it.

What you can do is have your class implement the interface then use its method fncAdd.

Upvotes: 2

Related Questions