C# Convert object to an unknown list of objects

Asked

Viewed 2,685 times

3

I have a question here.

I have an object (Object) received by parameter. It can be a single object or a list of objects (List).

Can I convert the object to a List object WITHOUT RECEIVING THE TYPE by parameter? I don’t want the method signed with .

An important limitation: I am using Framework 2.0. So, no Linux and other scripts that could help my life to be happier... rs...

-- adding more information, here is the question itself:

public class Conversor
{

    private class MinhaClasse
    {

        private string _meuNome;
        public string MeuNome
        {
            get { return _meuNome; }
            set { _meuNome = value; }
        }

        private int _minhaIdade;
        public int MinhaIdade
        {
            get { return _minhaIdade; }
            set { _minhaIdade = value; }
        }

    }

    public Conversor()
    {

        object lista = new List<MinhaClasse>();

        // E agora, como eu faço para transformar o objeto 'lista' em List<MinhaClasse> em tempo de execução para usar em um loop, por exemplo?
        // Lembrando que eu não quero assinar o método com o tipo genérico usando <T>, porque posso ter
        // que chamar o método de forma recursivo.


    }

}

Thank you.

  • Put your code in, give us a better context to understand what you need and give us a more suitable solution. We need to understand what information you have available, what should happen if it is not possible, if there are guarantees if it will always be possible, etc. I think you have better solution than you think.

  • Thanks for the @bigown reply. I added details as you soliciou.

  • What was missing is exactly how it will be used. The way it is just take that object and declare the list and it’s all right. I know this isn’t what you want, but the question doesn’t make it clear what you want.

  • From what I understand, you want the Converter not to have the responsibility to say the type, but to call the method, right?

  • At the end of the accounts, the converter will return me a string with the objects in JSON format... But as I do not have this feature native in . NET 2.0, I’m writing something a little more specific for the project I’m working on. This project is going to die soon, but I need it working.

1 answer

4


Your premise is somewhat wrong. Even though you have an instance object there is how to know the 'truth' type of this object.

At least in C#, all inheritance works this way: the "top-of-the-layer" type stores what is the actual type of the object.

This question has more details on this, even not talking directly on the subject.

A simple example: Imagine the classes Automovel, Carro and Fusca. You can do the following:

Automovel auto = new Fusca();

//Aqui é possível verificar se o objeto "auto" é do tipo Fusca ou algum outro

if(auto is Fusca)
    WriteLine("É um fusca")
else if(auto is Uno)
    WriteLine("É um uno");
else
    WriteLine($"É outro tipo de carro. Tipo: { auto.GetType() }");

See in practice, applied to your example (I used a list of string, but the idea is exactly the same):

using System.Collections;
using static System.Console;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        List<string> lista = new List<string> { "1", "2" };
        object obj = new object();

        Receber(lista);
        Receber(obj);

        ReadKey();
    }

    public static void Receber(object obj)
    {
        if (obj is IList)
        {
            WriteLine("É uma lista");

            foreach (var elemento in (IList)obj)
                WriteLine(elemento);
        }
        else
        {
            WriteLine("Não é uma lista");
        }
    }
}
  • Thanks for the answer. As I said in the post, I am using framework 2.0. There is no Ilist without passing the generic type it represents. I cannot go out testing with several if (Object is List<thing1...coisan>) because it would be, besides ugly, terrible to maintain.

  • For nothing, could you solve the problem? If yes, you can choose the answer as correct by marking the that is below the arrows to vote =)

  • I’m sorry... I entered before I finished writing. I haven’t solved the question yet.

  • Sorry. My mistake. I found the Ilist interface. Thanks, it helped me solve the case.

  • If I’m not mistaken, the interface IList exists in framework 2. Even if it did not exist, it is possible to do this check directly with List<T>, the idea is exactly the same. About the if's: you are complicating something that is simple, you can validate it in any way you like, in the answer I only show how you can do.

  • That’s right... you’re right :) Thank you very much...

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.