Friday, April 11, 2008

How to access explicit interface methods from another method

Explicit interface methods are prefered to instance members for following reasons

a) They are accessible only through interface

b) They support multiple levels of inheritance chain

Some insight. Take this example.

a) Take simple console application

b) Add an interface

c) Implement interface

d) Create Object of the class and try to access interface method

e) Cast it with interface and access

f) Call another explicit method method

g) Call another explicit methos by casting this object with interface

using System;
using System.Collections.Generic;
using System.Text;

namespace ClassMonitorLibrary
{

public class Program
{
//Entry point
public static void Main(String [] args)
{
#region Not accessible directly
//Object is accessible
//IFile im = (IFile)(new InterfaceMethods());
#endregion
InterfaceMethods im = new InterfaceMethods();
im.GetFile("Data.txt", 10);
}
}

//Simple interface
interface IFile
{
bool GetFile(string fileName, int length);
bool IsFileExists(string fileName);
}

//Interface implementation
class InterfaceMethods : IFile
{
bool IFile.GetFile(string fileName, int length)
{
#region how to access method
//if (((IFile)this).IsFileExists(fileName))
#endregion
if
(IsFileExists(fileName))
Console.WriteLine("FileExists");

return true;
}

bool IFile.IsFileExists(string fileName)
{
return true;
}
}
}

No comments: