Home > Back-end >  Convert type List<Object> to Object
Convert type List<Object> to Object

Time:07-20

I have the following class:

public class Up
{
    public string field { get; set; }
    public string oft { get; set; }
}

and I am calling the following function:

private Up GetUp()
    {
        var json = _fileSystem.File.ReadAllText(localPath);
        var cur = JsonConvert.DeserializeObject<List<Up>>(json);
        //Console.WriteLine(String.Join("\n", current)); 
        return cur;
    }

This gives an error:

Cannot implicitly convert type 'System.Collections.Generic.List<Up>' to 'Up'.

I am trying to return one object with multiple values so I can iterate over them. Is this even possible what I am trying to do here? (fairly new to C#).

CodePudding user response:

When you declare a method, its method signature defines the expected return type (among other things). The error you are seeing is letting you know that you currently have a System.Collections.Generic.List<Up>, but it (the compiler) was expecting Up to be returned by the method.

You are currently defining your method as:

private Up GetUp()

Which is telling the compiler that you want to define a method named GetUp, which is a private method, and which returns an Up object.

You probably want it's return type to be a List<Up>:

private List<Up> GetUp()

  •  Tags:  
  • c#
  • Related