19 October 2023

Can multiple datatype support in array and List in c#

 Can multiple datatype support in array and List in c#

In C#, arrays are collections of elements that must all have the same data type. This means that all elements in a C# array must be of a uniform data type. For example, if you create an array of integers, you cannot store other data types such as strings or floats in the same array.

Here's an example of creating an array of integers in C#:

```csharp

int[] numbers = new int[] { 1, 2, 3, 4, 5 };

In this example, `numbers` is an array of integers, and you can only store integer values in it. Attempting to store a different data type in this array would result in a compilation error.

If you need to store multiple data types in a collection, you can use other data structures in C# such as `List<T>` from the `System.Collections.Generic` namespace. `List<T>` allows you to store elements of different data types because it is a generic collection that can be parameterized with any data type.

Here's an example of using `List<T>` to store elements of different data types:

```csharp

using System;

using System.Collections.Generic;

class Program

{

    static void Main()

    {

        List<object> mixedList = new List<object>();

        mixedList.Add(1);        // integer

        mixedList.Add("hello");  // string

        mixedList.Add(3.14);     // double

        foreach (var item in mixedList)

        {

            Console.WriteLine(item);

        }

    }

}

In this example, `mixedList` is a `List<object>` that can store elements of different data types by treating them as `object`. However, it's important to note that using `List<object>` can lead to loss of type safety and may require explicit casting when retrieving elements from the list.

No comments:

Post a Comment

Comments Welcome

Implementing OAuth validation in a Web API

 I mplementing OAuth validation in a Web API Implementing OAuth validation in a Web API using C# typically involves several key steps to sec...