Question

I was wondering if there is a more aesthetic/easier to read way to write the following:

for (int i = 0; i < 100; i++)
{ 
    // If m.GetString(i) throws an exception, continue.
    // Otherwise, do stuff.       
    try
    {
        string s = m.GetString(i);
        continue;
    }           
    catch (InvalidCastException) 
    { 
    }

    // do stuff with the message that you know is not a string.
}

Here's what m looks like:

msg[0] = 10
msg[1] = "string"
msg[2] = 2.224574743
// Etc.
// Assume it's different every time.

So therefore when I do m.GetString(0) in this example, it throws an exception, as msg[0] is a uint and not a string. This is what I use to get the type, since m does not contain a GetType and I cannot edit m.

m is an instance of class Message in a library that I cannot edit.

However, despite this working just fine, it feels inefficient (and certainly not reader-friendly) to intentionally create exceptions, even if it's in a try-catch, in order to get the type.

Is there a better way or am I stuck with this?

Edit: Alright, I researched the Message class some more (which I should have done to begin with, my apologies). It is an IEnumerable<object>

Was it helpful?

Solution

Now that I know that m is an IEnumerable<object>, I think this is probably your best bet:

foreach (string s in m.OfType<string>())
{
    // Process s, which can't be null.
}

Nice and simple and it appears to handle all the logic that you want, i.e. it will process only the items in the sequence that are strings, and it will ignore all objects of other types.

However as Servy points out, this will not handle nulls in the list because null does not have any type at all.


[My previous answer before I knew the type of m]

I think you can take one of three approaches to this:

(1) Add a bool TryGetString(int index, out string) method to whatever type m is in your example and then do

if (m.TryGetString(i, out s)) 
    // Process s (need to check for null!) 

(2) Add a bool IsString(int index) method and call that before calling GetString().

if (m.IsString(i)) 
{
    s = m.GetString(i); 
    // Process s (need to check for null!) 

(3) Alternatively, you could expose the item via something like GetObject(int index) and then do something like Iiya suggested:

 string s = m.GetObject(i) as string; 

 if (s != null) 
     // Process s 

I think (1) or (3) would be best, although there might be a much better solution that we could suggest if we had more information about m.

OTHER TIPS

If you want to process only strings in a non-strongly typed sequence of data, use next code:

for (int i = 0; i < 100; i++)
{ 
    string s = m[i] as string;

    if(s != null)
    {

    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top