We help IT Professionals succeed at work.

Interfaces in C#?

woigl
woigl asked
on
Medium Priority
315 Views
Last Modified: 2010-04-16
Hi,

i am a JAVA developer and learning now C#...

Can someone tell me if Interfaces also in C# available? If yes how i can use them?

Kind Regards Stefan
Comment
Watch Question

Commented:
Yes. C# has Interfaces. They behave the same as in Java with two exceptions:
1.) C# Interfaces cannot have fields/constants like in Java.
2.) C# Interfaces do not allow for accessibility declarations (i.e. no 'public', 'private', 'protected', etc) in the interface.

Everything else is essentially the same.

Here are the official docs on it:
http://msdn2.microsoft.com/en-US/library/87d83y5b(VS.80).aspx

To summarize:

To create an interface:

public interface IAnimal
{
     void Eat();
     void Sleep();  
}

To implement an interface:

public class Dog : IAnimal
{
     public void Eat()
     {
         // Do some eating here
     }

     // Explicit interface definition, does not show up on Dog's Intellisense unless you cast it explicitly to an IAnimal reference
     void IAnimal.Sleep()
     {
          // Sleepy stuff here
     }
}

Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts
Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.