KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
OOC: Out Of Curiosity So, as a little exercise and for the sake of learning, I decided to check if I was able to implement a very basic recursive function that would return a List<int> , but with the following restrictions: 1- The result should be returned by the function itself (as opposed to passed as an argument to a void function). 2 - No local "named" variables declared in the function's body. I came up with the solution below (BTW: can this be improved in any way?) While doing this, I learnt that ToList() is not the same thing as casting to List<T> (see example below) - Anyone out there who can explain what happens under the hood and what the difference between the two is? Thanks! PS - I'm using version 4.0 (in case it matters). EDIT: the runtime error is Unable to cast object of type '<ConcatIterator>d__71'1[System.Int32]' to type 'System.Collections.Generic.List'1[System.Int32]' public static List<int> SomeIntegers(int min, int max) { //assume max >= min for simplicity if (min == max) return new List<int>() { min }; // runtime error //return (List<int>)(SomeIntegers(min, max - 1).Concat(new List<int>() { max })); //works return (SomeIntegers(min, max - 1).Concat(new List<int>() { max })).ToList(); }
Tags (comma-separated)
Save Edits
Cancel