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.
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With