Convert a class into an array

20,188

You can create an array "with your own hands" (see Arrays Tutorial):

String[] _chosenUser = new string[] 
{ 
    _user.key.ToString(), 
    _user.fullname,
    _user.username,
    _user.activated,
    _user.suspended
};

Or you could use Reflection (C# Programming Guide):

_chosenUser = _user.GetType()
                    .GetProperties()
                    .Select(p =>
                        {
                            object value = p.GetValue(_user, null);
                            return value == null ? null : value.ToString();
                        })
                    .ToArray();
Share:
20,188
Emmanuel Gabion
Author by

Emmanuel Gabion

Updated on July 05, 2022

Comments

  • Emmanuel Gabion
    Emmanuel Gabion almost 2 years

    I have a DisplayedData class ...

      public class DisplayedData
      {
        private int _key;
        private String _username;
        private String _fullName;
        private string _activated;
        private string _suspended;
    
    
        public int key { get { return _key; } set { _key = value; } }
        public string username { get { return _username; } set { _username = value; } }
        public string fullname { get { return _fullName; } set { _fullName = value; } }
        public string activated { get { return _activated; } set { _activated = value; } }
        public string suspended { get { return _suspended; } set { _suspended = value; } }
      }
    

    And I want to to put the objects from this class into an array where all objects inside of this class should be converted into an String[]

    I have..

    DisplayedData _user = new DisplayedData();
    String[] _chosenUser = _user. /* Im stuck here :)
    

    or can I create an array where all the items inside are consist of variables of different datatype so that the integer remains an integer and so the strings too?