ArrayTypeMismatchException In .NET

In this article we will explain how we can handle the ArrayTypeMismatchException in .NET.
  • 2562

Introduction

ArrayTypeMismatchException is thrown when an attempt is made to store an element of the wrong type within an array. Computer can't handle this situation without using exception handling so its gives an error or Exception.

Example

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text

 namespace ArrayTypeMismatch

{

    class Class1

    {

        static void Main(string[] args)

        {

            string[] names = { "Rahul", "Rohit", "Priya" };

            object[] objs = (object[])names;

            try

            {

                objs[2] = "Abhi";

             foreach (object Name in objs)

                {

                    System.Console.WriteLine(Name);

                }

            }

            catch (System.ArrayTypeMismatchException)

            {

                // Not reached; "Abhi" is of the correct type.

                System.Console.WriteLine("Exception Thrown.");

            }

            try

            {

                Object obj = (Object)13;

                objs[2] = obj;

             }

            catch (System.ArrayTypeMismatchException e)

            {

                Console.WriteLine(e.Message);

                // Always reached, 13 is not a string.

                System.Console.WriteLine( "New element is not of the correct type.");

            }

            // Set objs to an array of objects instead of 

            // an array of strings.

             objs = new Object[3];

            try

            {

                objs[0] = (Object)"Tuttor";

                objs[1] = (Object)8;

                objs[2] = (Object)12.12;

               foreach (object element in objs)

                {

                    System.Console.WriteLine(element);

                }

            }

            catch (System.ArrayTypeMismatchException)

            {

                // ArrayTypeMismatchException is not thrown this time.

                System.Console.WriteLine("Exception Thrown.");

            }

            Console.ReadLine();

        }

    }

}


The output of following program


Clipboard108.jpg

 

© 2020 DotNetHeaven. All rights reserved.