This C# Interview Question was asked my a member of this blog. Please refer to the example code below.
How to implement the void Method() of the interface in the following case ?
class B
{
public void Method()
{
// some code here
//...
}
}
Youtube video on Explicit Interface Implementation
interface I
{
void Method();
}
class D : B, I
{
// how to implement the void Method() of the interface
// public void I.Method() { ... }
}
To implement void Method, we use explicit interface implementation technique as shown below.
using System;
namespace SampleConsole
{
class Program
{
static void Main()
{
//To Call Class B Method
D d = new D();
d.Method();
//To Call the Interface Method
I i = new D();
i.Method();
//Another way to call Interface method
((I)d).Method();
}
}
class B
{
public void Method()
{
Console.WriteLine("Void Method - B");
}
}
interface I
{
void Method();
}
class D : B, I
{
void I.Method()
{
Console.WriteLine("Void Method - I");
}
}
}
Subscribe to:
Post Comments (Atom)
hi here am using 2 methods add(int x, int y) and add(double a,double b). So here am passing add(2,5) wchich method will firw and whts the reson. Give reply to my mail sandeepkumarvemula@gmail.com
ReplyDeleteadd(double a,double b)
Deleteby default all the integer numbers are treated as double.
@Umesh No you are wrong, here add(int x, int y) is going to fire. If the parameters values increases beyond int range then add(double a,double b) fire.
DeleteIf you call add(2,5) -> add(int x, int y) will fire.
DeleteFor add(2.5,5) or add(2,5.5) or add(2.5,5.5) -> add(double a,double b) will fire.
In your case, add(int x, int y) will be fired.
DeleteAs anonymous said, I confirm it.
If you call add(2,5) -> add(int x, int y) will fire.
For add(2.5,5) or add(2,5.5) or add(2.5,5.5) add( -> add(double a,double b) will fire.
OR if your number range exceeds the range of the integer number, double will be fired. For example, add(12345678912, 5);
Code to test this out:
class Program
{
static void Main(string[] args)
{
Program p = new Program();
p.add(10, 20);
p.add(10.5, 20.5);
p.add(12345678912, 5);
}
public void add(int a, int b)
{
Console.WriteLine("Integer is fired!");
}
public void add(double a, double b)
{
Console.WriteLine("Double is fired!");
}
}
add(int x, int y) this method
ReplyDeletewhat is difference between
ReplyDelete(==) and .equals in c#
== compares reference of objects in comparison and .Equal compares values of the objects in comparison
Delete