The following code I saw in one of StackOverflow sites. But it is not explained in detail and I am unable to understand. Would anyone explain this?
public class MyArray<T>
T array = new T;
public T GetItem(int index)
<T> have type parameters. Separate classes, each with a different field type in them, can be replaced with a single generic class. The generic class introduces a type parameter. This becomes part of the class definition itself. It allows you to define type-safe data structures, without committing to actual data types. The most common use of generics is to create collection classes. This results in a significant performance boost and higher quality code, because you get to reuse data processing algorithms without duplicating type-specific code.
T denotes a type that is only known based on the calling location. The program can act upon the instance of
T like it is a real type, but it is not.
I would like to know if this is a class.
Yes it is a class
How to instantiate this class?
MyArray<int> = new MyArray<int>();
MyArray<string> = new MyArray<string>();
Or anyother type you like
How can I use the T array in the class?
Since we know that one of the common use of generics is to create collection classes. So you can also use it that way.
Whether the array need to be created outside or inside in the class?
Question is little vague bcoz which class you are talking about the declaring class or the implementation class. But assuming that you are talking about the class where you implement or create the object of Class. It should be inside the class like normal object initiator.