Click here to Skip to main content
15,887,300 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How to take input from user for generic arrays?

What I have tried:

C#
class MyGenericArray<T>
{
    T[] arr;
    public MyGenericArray(int size)
    {
        T[] arr = new T[(size)];
        Console.WriteLine("Pls enter {0} no of values", size);
        for (int i = 0; i < size; i++)
        {
            arr[i] = Console.ReadLine() < T >; //am getting error here when i use convert.toint32(console.readline();-error states that generic cannot be converted to int.
        }
    }
Posted
Updated 8-Dec-17 7:22am
v3
Comments
F-ES Sitecore 8-Dec-17 5:47am    
If you're looking to use convert.ToInt32 then the text has to be representable as an int, so it's not generic, is it? It's an int. What if the user enter "true" or "false", or "Hello world"?

What is the overall aim of the code?

When you read from the console, it always returns a string.
You can't use a Generic specifier to change that to your required type, because that requires a specific Parse (or TryParse, or even Convert.ToXXX) method call to change it.

And there is no specific conversion from a string to any type (unlike in the opposite direction) because there is no way to "know" in advance what the data is, and how it should be converted.
It may be possible to set up a generic "convert from string to my type" method, but only if you add a constraint to the generic class that limits it to classes which implement an Interface which specifically requires such a conversion method to be defined by the class creator.
Unfortunately you can't "back-specify" that for existing built in classes such as the primitive int, double, float etc. so basically you can't do what you want at all.
 
Share this answer
 
As already pointed out, there's no standard way to convert a string to a specified class. But what you can do is pass in a delegate to do the conversion, which pushes that responsibility back onto the caller:
C#
class MyGenericArray<T>
{
    private readonly T[] arr;
    
    public MyGenericArray(int size, Func<string, T> parseValue)
    {
        arr = new T[size];
        
        Console.WriteLine("Pls enter {0} no of values", size);
        for (int i = 0; i < size; i++)
        {
            string value = Console.WriteLine();
            arr[i] = parseValue(value);
        }
    }
Usage:
C#
MyGenericArray<int> numbers = new MyGenericArray<int>(42, int.Parse);

MyGenericArray<Person> people = new MyGenericArray<Person>(5, value => new Person(value));

Using Delegates (C# Programming Guide) | Microsoft Docs[^]
Lambda Expressions (C# Programming Guide) | Microsoft Docs[^]
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900