Trebor
Trebor

Reputation: 813

How can I cast a class object to a list?

I'm fairly new to C# and I'm having trouble converting an object to a List<T>. I've been receiving the error "Cannot implicitly convert type Attachment to System.Collections.Generic.List<Attachment>. There are lots of posts about similar errors that I've looked over, but I can't seem to figure out what I'm missing.

My core object looks like:

public class Attachment 
{
    public Attachment() { }
    ...
}

It's being called in another class' constructor like so:

public class MyClass
{
    ...
    public List<Attachment> attachments { get; set; };
    ...
    public MyClass(JObject jobj)
    {
        ...
        //Attachments
        if (jobj["attachments"] != null)
        {
            attachments = (Attachment)jobj.Value<Attachment>("attachments");
        }
    }
}

The error is occurring in the last line of code where I'm trying to cast my Attachment object to the List<attachments>. I understand what the message is saying, but everything I've tried doesn't work.

Upvotes: 1

Views: 144

Answers (2)

EZI
EZI

Reputation: 15364

Simply use the ToObject method

List<Attachment> attachments = jobj["attachments"].ToObject<List<Attachment>>();

Upvotes: 3

Matthew Haugen
Matthew Haugen

Reputation: 13296

You are setting a List<T> to a T.

attachments = (Attachment)jobj.Value<Attachment>("attachments");

Instead, you probably want to Add it. But don't forget to instantiate the list first.

attachments = new List<Attachment>();
attachments.Add((Attachment)jobj.Value<Attachment>("attachments"));

Think about it in terms that don't involve generics. Say I have an int x and I set it to a string constant.

int x = "test";

What would that mean? Those are complete different types. That's kind of like the conversion you're asking the compiler to perform. The type on the left has to be (a polymorphic parent of or) the type on the right.

Upvotes: 6

Related Questions