tags:

views:

839

answers:

7

I have an arraylist that gets different type of values in it, 1st value->string,2nd value-> datetime, 3rd value--> boolean and 4th value is int, how do I find thier type and assign those values accordingly, any help is appreciated:)

here is my Code:

foreach (object obj in lstTop)
            {

              if(obj.GetType() == string)
                {do this...)
              else if(obj.GetType() == DateTime)
                {do this....}
              else if(obj.GetType() == bool)
                {do this....}
              else if(obj.GetType() == Int)
                {do this....}
            }

Thank you all, my Final Code:

string Subscription = "";
        DateTime issueFirst;
        DateTime issueEnd;

        foreach (object obj in lstTop)
        {
            ///Type t = obj.GetType();
            if (obj is string)
                Subscription += obj + ",";
            else if (obj is DateTime)
            {
               Subscription += Convert.ToDateTime(obj).ToShortDateString() + ",";
            }
           /// else if (t == typeof(DateTime))                
        }
    return ("User Authenticated user name: " + userName + ", Subscription: " + Subscription);
+2  A: 
foreach (object obj in lstTop)
        {

          if(obj is string)
            {do this...)
          else if(obj is DateTime)
            {do this....}
          else if(obj is bool)
            {do this....}
          else if(obj is Int)
            {do this....}
          else
          {
              // always have an else in case it falls through
              throw new Exception();
          }
        }
Jamie Ide
+2  A: 

ArrayLists in .Net 2.0 are almost always the wrong way to do it. Even if you don't know what the list will hold, you're better off using the generic List<Object> because that communicates to others that the list really could hold anything and isn't just a left over from a .Net 1.1 programmer.

Other than that, the is keyword should do what you want:

if (obj is string)
    // do this
else if (obj is DateTime)
    // do this
// ...

Update I know this is old, but it come up in my notices today. Reading it again, it occurs to me that another nice way to do this is via type resolution for an overloaded function:

void DoSomething(string value) { /* ... */ }
void DoSomething(DateTime value) { /* ... */ }

DoSomething(obj);
Joel Coehoorn
"But other than that, Mrs. Lincoln..."
mquander
+1  A: 

The simplest solution is not to use a loop since you know exactly what's in your list.

string   myString = (string)   lstTop[0];
DateTime myDate   = (DateTime) lstTop[1];
bool     myBool   = (bool)     lstTop[2];
int      myInt    = (int)      lstTop[3];
John Kugelman
The indexes may be different though. Not always reliable.
Adrian Godong
I wouldn't recommend this because the direct casts will throw runtime errors if the cast fails.
Jamie Ide
A: 

Just some slightly cleaner code:

foreach (object obj in lstTop)
        {

          if(obj is string)
            {do this...)
          else if(obj is DateTime)
            {do this....}
          else if(obj is bool)
            {do this....}
          else if(obj is int)
            {do this....}
        }

If your array always has the same objects in the same location though, just index into the array and do direct casts.

Will Eddins
A: 
        foreach (object obj in lstTop)
        {

          if(obj.GetType() == typeof(string))
            {do this...)
          else if(obj.GetType() == typeof(DateTime))
            {do this....}
          else if(obj.GetType() == typeof(bool))
            {do this....}
          else if(obj.GetType() == typeof(int))
            {do this....}
        }

The GetType method returns the System.Type of the object. Therefore you need to compare it with the another System.Type, which you get by using typeof.

Timothy Carter
+1  A: 

If your list contains exactly one value of each type you can store it in a Dictionary instead (if using an ArrayList is not a specific requirement), and just retrieve the value based on the requested type:

private Dictionary<Type, Object> data = GetDataList();
string myString = (string)data[typeof(string)];
int myInt = (int)data[typeof(int)];

This will make the process of fetching the values slightly more robust since it is not depending on the values appearing in any specific order.

Example of converting the ArrayList to such a dictionary:

ArrayList data = new ArrayList();
data.Add(1);
data.Add("a string");
data.Add(DateTime.Now);

Dictionary<Type, Object> dataDictionary = new Dictionary<Type, object>();
for (int i = 0; i < data.Count; i++)
{
    dataDictionary.Add(data[i].GetType(), data[i]);
}
Fredrik Mörk
A: 

Instead of using primitive types, I'd have an abstract class that encapsulated each data type. Then, the logic of handling that type can be embedded in the class itself.

foreach( MyBaseData data in lstData )
{
    data.DoTheRightThing();
}

In general, any code that switches on the type of an object should be considered a design smell - it may not necessarily be wrong, but it's probably a good idea to take another look at it.

While writing a class to encapsulate a simple type may feel like unnecessary work, I don't think I've ever regretted doing it.

kyoryu