Geeks With Blogs
Andy Johns' Blog Andy's twisted brain....

I've been coding some generic stuff lately and discovered something very cool, and something odd....

The Cool:

public IList<T> SomeMethod<T>(IList<T> listOfStuff) where T : ifoo

Can be called the normal way:

IList<foo> listOfStuff; // Somehow we get a list...
IList<foo> myStuff = MyObject.SomeMethod<foo>(listOfStuff);

However it can also be called:

IList<foo> myStuff = MyObject.SomeMethod(listOfStuff);

You don't need the <> definition on the generic method.... Very cool when refactoring from a type-specific method to a generic....

The Odd:

IList<ifoo> iFooList = (IList<ifoo>)new List<foo>();

List<ifoo> iFooList2 = (List<ifoo>)new List<foo>();

The first line (with the IList) will compile fine, but cause a runtime error, with a message that a list of foo cannot be cast to a list of ifoo.

The second will not compile, with a message that a list of foo cannot be cast to a list of ifoo.

Seems like if the compiler knows #2 is no good, it should know #1 is no good...

Of course what would be really cool is if you could cast it.... And yeah, I know you can't, still seems like the framework should be able too...

-Andy

Posted on Friday, March 23, 2007 1:39 PM | Back to top


Comments on this post: Two Generic things....

# re: Two Generic things....
Requesting Gravatar...
Quite inspiring,

Do you mind explaine why some people use Ienumreble as a method return type(isn't it an interface!)

Keep up the good work
Left by web development company on Aug 19, 2009 10:59 AM

Your comment:
 (will show your gravatar)


Copyright © Andy Johns | Powered by: GeeksWithBlogs.net