Monday, March 28, 2011

C# equivalent of Java 'implements' keyword?

In Java if you were to have the statement:

public class MyClass implements LargerClass {

Would you be extending the LargerClass with more methods?

What would be the equivalent of this class definition in C#?

I ask because I am not very familiar with Java and am currently converting some Java code to C# code and this one is giving me some trouble.

Thanks in advance.

From stackoverflow
  • public class MyClass : LargerClass
    {
    
    }
    
  • public class MyClass : LargerClass {...}
    
  • Implements means you "implement an interface" and there is no need for any statement in C#, just list the interfaces you implement.

    EDIT: BTW you can only derive from a single class, and implement as many interfaces as you want. The requirement is that you name the parent class first and the interfaces next.

  • public class MyClass implements LargerClass
    

    In Java, this declares that MyClass implements the interface LargerClass; that is, sets out implementations for the behaviours defined in LargerClass.

    To inherit from another class in Java, use extends, e.g.

    public class MyClass extends LargerClass
    

    The C# equivalent, in both cases, is specified as

    public class MyClass : LargerClass
    

    Since this syntax doesn't make it clear whether or not LargerClass is an interface or another class being inherited, you'll find C#/.NET developers adopt the convention that interface names are prefixed with uppercase "I", e.g. IEnumerable.

    Outlaw Programmer : I like this answer better because it mentions the standard convention you can use to differentiate between interfaces and classes.

0 comments:

Post a Comment