C# - Interface Class

R

Richard

Hi,



I'm new to C# and are having difficultly implementing an interface class.
Basically I want to define an interface class, then inherit it. I want some
of the methods to be public, and some not. Below is an example of what I'm
trying to do;



using System;

public interface iTCPInterface : IDisposable

{

void Connected();

void Close();

string DataArrival();

}





public class clsAttempt1 : iTCPInterface

{

public void Connected()

{}

public void Close()

{}



public string DataArrival()

{return "boo";}

public void Dispose()

{}

}





The above will compile without any issues. However, I don't want anything
being able to call public void close when I create an instance of
clsAttempt1. Now I would have thought that by saying "Private void Close()"
I would achieve this. Alas, here is my problem. When I do this I get a
compile error:



'clsAttempt1' does not implement interface member 'iTCPInterface.Close()'.
'clsAttempt1.Close()' is either static, not public, or has the wrong return
type.



Where have I gone wrong? I don't want Close accessible outside of the class
e.g. myObject.Close.





Thanks in advance.
 
M

Mattias Sjögren

Where have I gone wrong? I don't want Close accessible outside of the class
e.g. myObject.Close.

Then you shouldn't implement an interface with such a method.

You can implement the method privately using explicit implementation

void ITCPInterface.Close() {... }

but it will still be callable from the outside through a ITCPInterface
reference.



Mattias
 
D

Dmitriy Lapshin [C# / .NET MVP]

Hi Richard,

Here's the trick:

public class clsAttempt1 : iTCPInterface
{
void iTCPInterface.Connected()
{}
void iTCPInterface.Close()
{}
}

This way, the Connected and Close methods will be accessible only through
the interface but not the implementing class itself.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top