0

I'm trying to understand the -why- of this ... and I'm really struggling to grasp the concept of what I'm telling the compiler to do when I use an IInterface syntax. Can anyone explain it in a "this is what's going on" way?

Anyway ... my main question is....

What is the difference between

public IEnumerable<string> MyMethod() {...}

and

public string MyMethod() : IEnumerable {...}

Why would you use one over the other?

1
  • Your second example isn't valid code. (I'm assuming you mean C# - it would be worth tagging the question.) If you can make both examples valid, we'll tell you the remaining differences. Commented Apr 2, 2009 at 22:46

3 Answers 3

4
public string MyMethod() : IEnumerable {...}

Will not compile, that's one difference.

But you could have

public class MyClass : IEnumerable<string> {...}

And then

public IEnumerable<string> MyMethod() 
{
   MyClass mc = new MyClass();
   return mc;
}
Sign up to request clarification or add additional context in comments.

Comments

1

When you say public IEnumerable<string> MyMethod() {...} , you are declaring a method which returns some instance that implements IEnumerable<string>. This instance might be an array of string, a List<string>, or some type that you make.

When you say public class MyClass : IEnumerable<string> {...}, you are declaring a type which implements IEnumerable<string>. An instance of MyClass could be returned by MyMethod.

Comments

0

the first is a valid method declaration, as long as it is living in a Class ie

class MyClass 
{
    public IEnumerable<string> MyMethod() {...}
}

the second is not valid C# and will not compile. It is close to a Class declaration, tho.

class MyClass : IEnumerable<string>
{

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.