getting error While executing the code below in C#
using System;
using System.Collections.Generic;
namespace GenericApplication {
public class MyGenericApplication < T > {
private T[] array;public static MyGenericArray(int size) {
return MyGenericArray[size];
}
public T getItem(int index) {
return array[index];
}
public void setItem(int index, T value) {
return array[index] = value;
}
}
class tester {
public static void Main(string[] args) {
MyGenericArray < int > intArray = new MyGenericArray < int > (5);
for (int c = 0; c < 5; c++) {
setItem(c, c * 5);
}
for (int c = 0; c < 5; c++) {
Write(intArray.getItem(c) + " ");
}
WriteLine();
MyGenericArray < char > charArray = new MyGenericArray < char > (5);
for (int c = 0; c < 5; c++) {
setItem(c, (char)(c + 97));
}
for (int c = 0; c < 5; c++) {
Write(charArray.getItem(c) + " ");
}
WriteLine();
}
}
}
main.cs(10,19): error CS1520: Class, struct, or interface method must have a return type
Your code had lots of issues, here is the correct code, with explanation in comments, you are using generic type data to inittialize , set and get values of arrays
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class tester
{
public static void Main(string[] args)
{
//Initialize array of int type
MyGenericArray<int> intArray = new MyGenericArray<int>(5);
//Set items in array one bye one by loop
for (int c = 0; c < 5; c++)
{
intArray.setItem(c, c * 5);
}
//Get Items of Array set in above steps
for (int c = 0; c < 5; c++)
{
Console.Write(intArray.getItem(c) + " ");
}
Console.WriteLine();
//repeat above steps again using char type instead of int
MyGenericArray<char> charArray = new MyGenericArray<char>(5);
for (int c = 0; c < 5; c++)
{
charArray.setItem(c, (char)(c + 97));
}
for (int c = 0; c < 5; c++)
{
Console.Write(charArray.getItem(c) + " ");
}
Console.WriteLine();
}
//Create private class of generic type
private class MyGenericArray<T>
{
private int v;
private T[] array= new T[5];
//set the Generic type array length
public MyGenericArray(int v)
{
this.v = v;
}
//get array items
public T getItem(int index)
{
return array[index];
}
//set array items, at Index for example 1, where value = value of type T(int, char)
public T setItem(int index, T value)
{
//example array[0]=0
//array [1]=5
//array [2]=10
return array[index] =value;
}
}
}
}
try this link
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly