Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a default type for T in a static generic method?

Tags:

c#

generics

I am working with my own custom stacks class, and I am trying to create a generic method for creating a new stack(a generic object). I work a lot with stacks that are type int, and only occasionally need other types. Can I set the defult Type of T to int?

Here is the method:

public static Stack<T> newStack<T>(int length)
{
    Stack<T> s = new Stack<T>();
    for (int i = 0; i < length; i++)
    {
        Console.WriteLine("print num");
        string input = Console.ReadLine();
        T value = (T)Convert.ChangeType(input, typeof(T));
        s.Push(value);
    }
    return s;
}

I want to use the method like this:

newStack(5);//defult int type

and for any other type

newStack<string>(5)

Can anybody help? Thanks.

like image 206
INTODAN Avatar asked Dec 23 '22 19:12

INTODAN


2 Answers

You can't specify a default type for T however you can simply overload the newStack method to get the behaviour you want. The overloaded method will automatically create a new stack of type int.

Your code would look something like this:

public static Stack<T> newStack<T>(int length)
{
    Stack<T> s = new Stack<T>();
    for (int i = 0; i < length; i++)
    {
        Console.WriteLine("print num");
        string input = Console.ReadLine();
        T value = (T)Convert.ChangeType(input, typeof(T));
        s.Push(value);
    }
    return s;
}

public static Stack<int> newStack(int length)
{
    // Call our original new stack method but pass
    // integer as the type T
    return newStack<int>(length);
}

Now you can call the second method if you just want to create a new stack of type integer like this:

newStack(5);

Otherwise you can create stacks of other types with:

newStack<string>(5);
like image 68
Ivan Kahl Avatar answered Mar 03 '23 17:03

Ivan Kahl


Add a method newStack without the generics:

 public static Stack<int> newStack(int length) => newStack<int>(length);

The compiler is smart enough to select the correct method.

like image 39
GvS Avatar answered Mar 03 '23 17:03

GvS