Quiz 1: Generic class with static fields
In the following piece of code you can see 2 instantiations of a generic class. What is the output of this console application?
using System;
using System.Collections.Generic;
namespace DEMO
{
class Program
{
static void Main(string[] args)
{
GenClass<int> x = new GenClass<int>();
GenClass<double> y = new GenClass<double>();
x.Add(1);
y.Add(2);
Console.WriteLine(y.Get(0));
}
public class GenClass<T>
{
public static List<T> list = new List<T>();
public void Add(T x)
{
list.Add(x);
}
public string Get(int index)
{
return list[index].ToString();
}
}
}
}
I'll post the response in a comment.
3 comments:
The output of the console application is 2.
.NET interpretes the GenClass<int> and GenClass<double> as 2 different types. This means that each type has its own static list.
Each of the types will have a static list with only one value in it. For the instance y this will be the value 2.
Thanks for your effort , i think we need your posts about .net 3.5 :).
Thanks
yes, actually generics are like templates not types, and all the type information is attched with type so when we create a type sat genclass <Int> or genclass<myclass>
or say List<country> then these static fields are attched with that type.
Post a Comment