Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get object type and assign values accordingly

Tags:

c#

.net

.net-2.0

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);
like image 797
Developer Avatar asked Jul 10 '09 15:07

Developer


2 Answers

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();
          }
        }
like image 171
Jamie Ide Avatar answered Oct 03 '22 07:10

Jamie Ide


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);
like image 20
Joel Coehoorn Avatar answered Oct 03 '22 08:10

Joel Coehoorn