infotechelg
asked on
Conversion from Object to Struct or Class in C#
I'm creating an extension method of various classes and structs (string, int, double, etc) called "Or", which basically would work like T-SQL's "IN" function.
Anyway, here are the three extensions:
My question is, is there a way to do the following code that appears in all three methods so I only have to write it once?
Obviously, there'd have to be some way to pass these into some method as objects then determine what those objects are?
Hope this all makes sense. :)
Anyway, here are the three extensions:
internal static class Extensions
{
internal static bool Or(this int i, int[] list)
{
bool retval = false;
foreach (int val in list)
{
if (i == val)
{
retval = true;
break;
}
}
return retval;
}
internal static bool Or(this double d, double[] list)
{
bool retval = false;
foreach (double val in list)
{
if (d == val)
{
retval = true;
break;
}
}
return retval;
}
internal static bool Or(this string s, string[] list)
{
bool retval = false;
foreach (string val in list)
{
if (s == val)
{
retval = true;
break;
}
}
return retval;
}
My question is, is there a way to do the following code that appears in all three methods so I only have to write it once?
foreach (int val in list)
{
if (i == val)
{
retval = true;
break;
}
}
Obviously, there'd have to be some way to pass these into some method as objects then determine what those objects are?
Hope this all makes sense. :)
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
NP. Glad to help = )
I screwed up the calling examples, in case you didn't figure it out. For the benefit of future readers, the way to call the method would be like this:
I screwed up the calling examples, in case you didn't figure it out. For the benefit of future readers, the way to call the method would be like this:
double val = 4;
double[] values = { 3, 3, 5, 6, };
bool found = val.Or<double>(values);
--OR--
string val = "hello";
string[] values = { "hello world!", "goodbye world!" };
bool found = val.Or<string>(values);
hi
you can do like that:
you can do like that:
internal static bool Or(this object i, ArrayList list)
{
bool retval = false;
foreach (object val in list)
{
if (i.Equals( val))
{
retval = true;
break;
}
}
return retval;
}
@safiint
Why would you want to have all that boxing/unboxing going on??
Why would you want to have all that boxing/unboxing going on??
ASKER