5
Answers

Interface

Maha

Maha

10y
976
1
It is said that public modifier is used to access a class from outside.

public void IA1.Foo1() method is not accessible from the main method. But
void IA1.Foo1() method is accessible from the main method. Please tell me reason. Problem is highlighted. 

using System;

interface IA1
{
void Foo1();
}

class CA : IA1
{
public void IA1.Foo1()
{
Console.WriteLine("In Foo2 of CA");
}
}

class Program
{
static void Main(string[] args)
{
IA1 a1; CA a;
a = new CA();
a1 = new CA();

a1.Foo1();

Console.ReadKey();
}
}

Answers (5)
1
Vulpes
NA 98.3k 1.5m 10y
Implementing an interface method explicitly is a bit weird because it is private in one sense and public in another!

A method such as IA1.Foo1 can not be accessed publicly using a CA reference and so it is private in that sense. However, it can be accessed publicly using an IA1 reference and so it is public in that sense.

Also, the weirdness doesn't end there. Even if you want to access it privately from within the class, you still need to do it using an IA1 reference - you can't just use 'this'.
 
Because of this behavior, the designers of the C# language decided that it would be misleading to allow it to carry the public access modifier (or indeed any access modifier) and therefore simply disallowed this.

I've extended your example to illustrate how you can access IA1.Foo1 both from outside and within the CA class:


using System;

interface IA1
{
   void Foo1();
}

class CA : IA1
{
   void IA1.Foo1() // no access modifier allowed
   {
      Console.WriteLine("In Foo2 of CA");
   }

   public void SomeMethod()
   {
      ((IA1)this).Foo1(); // still need an IA1 reference to access privately
   }

}

class Program
{
   static void Main(string[] args)
   {
      IA1 a1; CA a;
      a = new CA();
      a1 = new CA();
      a.SomeMethod();
      a1.Foo1(); // need an IA1 reference to access publicly  
      Console.ReadKey();
   }

0
Gowtham Rajamanickam
NA 23.9k 2.9m 10y
use the name 1A1.Foo1() for interface method
0
Maha
NA 631 42.9k 10y
Thank you for your explanation Pankaj Kumar Choudhary.
0
Pankaj  Kumar Choudhary
NA 29.8k 3.1m 10y
hello @maha mem  Public Void 1A1.Foo1() this method of implementation of a  interface method   is known as " Explicit Interface Implementation" according this method "


A class that implements an interface can explicitly implement a member of that interface. When a member is explicitly implemented, it cannot be accessed through a class instance, but only through an instance of the interface. "


In Explicit Interface Implementation we can only access the method of explicit interface uing the instance of an interface.
 we use the name 1A1.Foo1() for interface method


This name mechanism  also known as fully qualified name.
because it provide a fully name of  an method








0
Maha
NA 631 42.9k 10y
Thank you for your explanation.