Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7972789
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 4, 20262026-06-04T07:57:08+00:00 2026-06-04T07:57:08+00:00

Ok, lets say I have an array of objects in C# .Net like so:

  • 0

Ok, lets say I have an array of objects in C# .Net like so:

object[] myObjects = new object[9];
myObjects[0] = "Foo";
myObjects[1] = 3;
myObjects[2] = 2.75;
myObjects[3] = "Bar";
myObjects[4] = 675;
myObjects[5] = "FooBar";
myObjects[6] = 12;
myObjects[7] = 11;
myObjects[8] = "FooBarFooBar";

I want to, inside a foreach block, enumerate this array and write every string to a text document using StreamWriter like so:

StreamWriter sw = new StreamWriter(@"C:\z\foobar.txt");

foreach(string myObject in myObjects)
{
    sw.WriteLine(myObject);
}

sw.Flush();
sw.Close();

My problem is that whenever I try to cast the integers and doubles to String, an exception will be thrown.

If I put a try/catch block around my foreach statement, the exception that gets thrown on the second iteration will trigger the catching of the exception and nothing will get written to my text document.

Putting the try/catch inside the foreach is pointless because the exception happens on the cast.

I want to use a foreach loop (let’s assume that for loops don’t exist, and that we can’t use indexing or ToString()) to enumerate an array of objects, casting each to a string and writing these to a text document using StreamWriter. If the cast works, happy days. If not, I want to catch the exception thrown and continue to enumerate the remaining objects.

Thanks

Edit: Before somebody says it, this isn’t homework! I am trying to solve a real world problem.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-04T07:57:09+00:00Added an answer on June 4, 2026 at 7:57 am

    Because you expect a heterogeneous collection, it’s better to avoid throwing InvalidCastException in the first place. Read up on “boneheaded exceptions” in Eric Lippert’s excellent Vexing exceptions article.

    Option 1: Use the LINQ OfType<TResult>() extension method to pick out only elements of a specified type:

    // using System.Linq;
    
    foreach(string myObject in myObjects.OfType<string>())
    {
        sw.WriteLine(myObject);
    }
    

    Option 2: Do the type check yourself:

    foreach(object myObject in myObjects)
    {
        string s = myObject as string;
        if (s != null)
            sw.WriteLine(s);
    }
    

    This option is easy to extend to handle multiple types.

    UPDATE:

    Ok, but what would happen if, in some outlandish scenario, an exception was still thrown on this line. Is there a way to handle the exception and then continue with my enumeration?

    Here are the other ways an exception could be thrown on the foreach line, none of which you can sensibly handle:

    • myObjects.GetEnumerator() throws an exception. In this case, the enumeration can’t be started at all.
    • IEnumerator<string>.MoveNext() throws an exception. In this case, the enumerator is likely to be corrupt, and enumeration cannot continue.
    • Some other type of fatal exception occurs: OutOfMemoryException, StackOverflowException, etc. In this case, you should just let the process die.
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Lets say I have an array with a structure like this: $arr= Array( array(
Lets say I have the following array in JavaScript: var skins = new Array('Light',
Lets say you have various objects of arbitrary type that you would like to
I have an Array with some String objects lets say months. [October] [May] [July]
Lets say I have an array of javascript objects, and I am trying to
I have an array and lets say I have 5 objects in it. The
Lets say you have an program like this: $info = array( 'username'=>'jeff', 'password'=>'kay' );
Let's say I have an array of custom objects. The custom class looks like
Let's say I have an array of objects [{href: 'some_uri', 'class': 'this-css-class'}, {href: 'another_uri',
Let's say I have an array of primitives or a list of objects, doesn't

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.