Reputation:
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?
Upvotes: 0
Views: 163
Reputation: 29216
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>
{
}
Upvotes: 0
Reputation: 273244
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;
}
Upvotes: 4
Reputation: 110111
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.
Upvotes: 1