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);
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();
}
}
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With