Lowest price ever! Learn Generative AI for 48% less!
Get my discount0
Generic Classes
I've been stuck on this problem for a while and I can't seem to figure it out!!! using System; using System.Collections.Generic; namespace SoloLearn { class Program { static void Main(string[] args) { Elems<string> elems1 = new Elems<string>(); elems1.Add("John", "Tamara", "David"); elems1.Show(); Console.WriteLine(); Elems<int> elems2 = new Elems<int>(); elems2.Add(5, 14, 13); elems2.Show(); } } //make this class generic class Elems { public int[] elements = new int[3]; public void Add(int elem1, int elem2, int elem3) { elements[0] = elem1; elements[1] = elem2; elements[2] = elem3; } public void Show() { foreach (int item in elements) { Console.Write(item + " "); } } } }
2 Answers
+ 2
using System;
using System.Collections.Generic;
namespace SoloLearn
{
class Program
{
static void Main(string[] args)
{
Elems<string> elems1 = new Elems<string>();
elems1.Add("John", "Tamara", "David");
elems1.Show();
Console.WriteLine();
Elems<int> elems2 = new Elems<int>();
elems2.Add(5, 14, 13);
elems2.Show();
}
}
//make this class generic
class Elems<T>
{
public T[] elements = new T[3];
public void Add(T elem1, T elem2, T elem3)
{
elements[0] = elem1;
elements[1] = elem2;
elements[2] = elem3;
}
public void Show()
{
foreach (T item in elements)
{
Console.Write(item + " ");
}
}
}
}
0
Please revise the chapter, all these are covered in the lesson.
Basically, the `Elems` class is not correctly setup as a generic class. No generic specification used in class definition, the internal storage array <elements>, the arguments of Add() method, and the foreach...loop inside Show() method.
You may also refer external resources for additional info.
https://www.javatpoint.com/c-sharp-generics