Thursday, March 1, 2012

var in c#

why does c# have a var keyword ?
if you answer because of linq- that would be partly correct
consider:
Type t = this.GetType();
PropertyInfo[] p = t.GetProperties();
var names = from nms in p select nms.Name;

in this case the var is not necessary

the following could be written


We need var in a case where we are using implicitly typed local variables:

this.listBox1.Items.Clear();
            Type t = this.GetType();
            PropertyInfo[] p = t.GetProperties();
            var names = from nms in p select new {Name = nms.Name,Typ =nms.PropertyType};
            foreach (var s in names)
            {
                this.listBox1.Items.Add(s.Name +" "+ s.Typ.ToString());  
            }



IEnumerable<string> names = from nms in p select nms.Name;

No comments:

Post a Comment