1

So I'm building a small application in C# where I have an IEnumerable that I want to cast into a List. This is what I got:

var enumerable = SettingsManager.ReadSettings();
var list = enumerable.Cast<Setting>().ToList();

The compiler says that ReadSettings cannot be inferred from the usage. This is how ReadSettings look like:

public static IEnumerable<T> ReadSettings<T>()
{
     //Code omitted
     return JsonConvert.DeserializeObject<T[]>(fileAsString).ToList<T>();
}
Mafii
  • 7,227
  • 1
  • 35
  • 55
pidde2
  • 11
  • 2
  • You are not giving a type to 'ReadSettings<>()' when you are setting 'enumerable' – Travis Tubbs Jul 24 '17 at 12:58
  • When using Newtonsoft.Json serializer, you can replace `JsonConvert.DeserializeObject(fileAsString).ToList()` by `JsonConvert.DeserializeObject>(fileAsString)` or even `IList`, `IEnumerable` – Uwy Jul 24 '17 at 13:09

2 Answers2

7

If your method is generic, you should provide a generic type-parameter. From your usage I suppose you´re after the type Setting, so your correct code was something like this:

var enumerable = SettingsManager.ReadSettings<Setting>();
var list = enumerable.ToList();

Now enumerable has a strong type known at compile-time, which is why you can omit casting every element within that list to the Setting-type.

If you don´t know the actual type at runtime you´re stuck on using reflection as mentioned in this post.

EDIT: As your ReadSettings-method actually produces a list by calling ToList you could omit the explicit second ToList-call on the second line and cast to List<T> instead. Alternativly - and imho better - was to omit that call within ReadSettings.

MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111
4

You are missing T specification for ReadSetting. You need code like this:

var list= SettingsManager.ReadSettings<Setting>();
// continue here
Pavel Pája Halbich
  • 1,529
  • 2
  • 17
  • 22
  • This will give OP an `IEnumerable`, not a `List` – DavidG Jul 24 '17 at 13:01
  • @DavidG I believe calling `ToList()` depends on further usage. And since OP used this method, I didn't include it in my code. – Pavel Pája Halbich Jul 24 '17 at 13:04
  • 1
    @DavidG And their example code specifically creates a list from the enumerable on the very next line. This code corrects the error, and the resulting code does exactly what the user asked for. – Bradley Uffner Jul 24 '17 at 13:10
  • @DavidG well, if you look on `ReadSettings` method, there is already one `ToList`. I don't see any example why create data, take them to List, then use them as IEnumerable and then taking it to List again. – Pavel Pája Halbich Jul 24 '17 at 13:10
  • @BradleyUffner But this answer goes directly to the `list` variable and combines both lines form the question. – DavidG Jul 24 '17 at 13:10
  • 2
    @PavelPájaHalbich But the return type of the method is `IEnumerable` so while you've created a `List`, it's stored in a different type. – DavidG Jul 24 '17 at 13:11