Why can't we declare var a = new List <string> at the class level?
I know that we cannot do this at the class level, but at the method level we can always do this.
var myList=new List<string> // or something else like this
This question came to my mind as we declare a variable like this. We always provide type information in RHS expressions. Therefore, the compiler does not need to do type guessing. (correct me if I am wrong).
therefore, the question remains WHY NOT at the class level until it is resolved at the method level
+5
5 answers
Generic referral list type
class Class1
{
public void genmethod<T>(T i,int Count)
{
List<string> list = i as List<string>;
for (int j = 0; j < Count; j++)
{
Console.WriteLine(list[j]);
}
}
static void Main(string[] args)
{
Class1 c = new Class1();
c.genmethod<string>("str",0);
List<string> l = new List<string>();
l.Add("a");
l.Add("b");
l.Add("c");
l.Add("d");
c.genmethod<List<string>>(l,l.Count);
Console.WriteLine("abc");
Console.ReadLine();
}
}
0