Want to become a Vibe Coder? Join Vibe Coding Training here
x
C# Corner
Tech
News
Videos
Forums
Jobs
Books
Events
More
Interviews
Live
Learn
Training
Career
Members
Blogs
Challenges
Certification
Bounty
Contribute
Article
Blog
Video
Ebook
Interview Question
Collapse
Feed
Dashboard
Wallet
Learn
Achievements
Network
Refer
Rewards
SharpGPT
Premium
Contribute
Article
Blog
Video
Ebook
Interview Question
Register
Login
Explicit Interface Implementation in C#
WhatsApp
Harieswaran D
10y
4.1
k
0
0
25
Blog
Explicit Interface Implementation
Simple explanation of how to explicitly implement interface and how to access those interface members from the interface instances.
A class can explicitly implement the interface members.
By this ways of implementing the explicit interface, we can have a class implementing multiple interface with same member definition.
Now let’s see in following code how to explicitly implement interface members and also how to differentiate interface members having same member definition across multiple interface.
Code
using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Text;
namespace
Explicit_interface
{
interface
capswriter
{
string
writename();
}
interface
smallwriter
{
string
writename();
}
class
caption : capswriter, smallwriter
{
string
firstname;
public
caption(
string
N)
{
this
.firstname = N;
}
string
capswriter.writename()
{
return
this
.firstname.ToUpper();
}
string
smallwriter.writename()
{
return
this
.firstname.ToLower();
}
}
class
Program
{
static
void
Main(
string
[] args)
{
caption obj =
new
caption(
"Harish Sady"
);
capswriter obj_caps = (capswriter)obj;
smallwriter obj_small = (smallwriter)obj;
Console.WriteLine(
"-- Output of capswriter Interface---"
);
Console.WriteLine(obj_caps.writename());
Console.WriteLine(
"-- Output of smallwriter Interface---"
);
Console.WriteLine(obj_small.writename());
Console.ReadKey();
}
}
}
Explanation
caption obj =
new
caption(
"Harish Sady"
);
Since we have mention the interface members explicitly, we cannot access those interface members using class objects.
To access those members, we should cast the class object to respective interface.
capswriter obj_caps = (capswriter)obj;
So class objects is casted to “capswriter” interface.
Now we can access the “writename” method by the interface instance.
Output
People also reading
Membership not found