xxxxxxxxxx
Okay, imagine you have a box of crayons. Each crayon has a specific color, right? Now, think of a C# interface like a coloring book page. The coloring book page has outlines of different shapes and pictures, but it doesn't have any colors yet.
In C#, a class is like a set of crayons with actual colors. It's a blueprint that tells you what the crayons should look like and what colors they should have. When you create an object from a class, it's like having a physical crayon from that set with all the colors filled in.
Now, an interface in C# is a bit like a blank coloring book page. It doesn't have any colors (methods or properties with implementation) of its own. Instead, it just says, "Hey, if you want to use me, you need to promise that you'll have these colors (methods or properties)." It sets the rules but doesn't provide the actual implementation.
So, while a class gives you the actual crayons with colors, an interface tells you what colors you should have without providing them. It's like a contract that says, "If you want to be my friend (use this interface), you need to know how to say hello (implement these methods)."
To sum it up, a class is like having a complete set of crayons with colors, and an interface is like a coloring book page that outlines what colors you should have without filling them in.
xxxxxxxxxx
using System;
namespace Grepper_Docs
{
public interface IWhatever
{
bool doSomething(); //Interface methods don't have bodies or modifiers
}
class Program : IWhatever
{
static void Main(string[] args)
{
var pro = new Program();
pro.doSomething();
}
public bool doSomething() //methods must be public
{
return true;
}
}
}
xxxxxxxxxx
using System;
namespace InterfaceDemo
{
public interface IA
{
void puta();
}
public interface IB
{
void putb();
}
public class C: IA, IB
{
private int a;
private int b;
public C(int x, int y)
{
a = x;
b = y;
}
public void puta()
{
Console.WriteLine("a = {0}", a);
}
public void putb()
{
Console.WriteLine("b = {0}", b);
}
}
class Test
{
static void Main(string[] args)
{
C obj = new C(17, 4);
obj.puta();
obj.putb();
}
}
}
xxxxxxxxxx
// C# program to demonstrate working of
// interface
using System;
// A simple interface
interface inter1
{
// method having only declaration
// not definition
void display();
}
// A class that implements interface.
class testClass : inter1
{
// providing the body part of function
public void display()
{
Console.WriteLine("Sudo Placement GeeksforGeeks");
}
// Main Method
public static void Main (String []args)
{
// Creating object
testClass t = new testClass();
// calling method
t.display();
}
}