views:

114

answers:

3

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?

Thanks, Simon

+4  A: 
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;
}
Henk Holterman
+1  A: 

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.

David B
A: 

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>
{

}
Muad'Dib