0

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 + " "); } } } }

27th Jul 2022, 2:22 PM
Chris
Chris - avatar
2 ответов
+ 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 + " "); } } } }
22nd Feb 2023, 8:53 PM
Deepika. Shetty
Deepika. Shetty - avatar
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
27th Jul 2022, 3:03 PM
Ipang