This is an explanation of why the var “keyword” is like it is, and how this effects anonymous classes. I should probably point out I’m nothing to do with the C# design team, so these are merely my own opinions.<?xml:namespace prefix = o ns = “urn:schemas-microsoft-com:office:office” />/o:p

 /o:p

The var is all about type inference, it’s important to remember this is still static typing. The var keyword informs the compiler that it should try and infer the type of variable; if it can not do this a compile error is generated. One very important aspect of the var keyword is that it can only be used with local variables, and even then are a few cases that are not allowed./o:p

 /o:p

The nemerle project, which has a very similar type inference system, has a web site which has this interesting discussion on type inference. To paraphrase them more than I probable should, the reason they don’t offer type inference on anything other than local variables is that the only way the type of a parameter can be inferred is when the method is called, and a method may not actually be called. (Okay, they allow type inference on parameters of local functions, but these are local variables that just happen to functions)/o:p

 /o:p

However, for C# there is an even greater motivation than this for limiting the var keyword to local variables – backwards compatibility. “var” is not really a keyword in the strictest sense of the term, because it is forbidden to use keywords as class/struct/method/parameter/variable names and it is okay to use var in this way. This is problematic because could have a class called var, so this means we need some mechanism to know whether or not we are referring to the keyword var or the class var. In C# this is what is on the right had side of the statement, and if we where to allow the keyword var to be used as a method parameter then we could never know which one we meant, because there is no right hand side of the statement for a parameter. That’s an awful lot of talking so let’s look at a quick example, imagined the following:/o:p

 /o:p

public class var { … } /o:p

 /o:p

public class Program/o:p

{/o:p

         public void MyMethod (var thing1, // does this mean var keyword or var class??/o:p

                   string thing2,/o:p

                   int thing3)/o:p

         {/o:p

                   var myString = “Hello, world”;/o:p

                            // var here means string (System.String)/o:p

                   var myInt = 1;/o:p

                            // var here means int (System.Int32)/o:p

                   var myVar = new var();/o:p

                            // var here means the class var/o:p

                   var myVar2 = null;/o:p

// does this mean var keyword or var class??/o:p

                   var myVar3;/o:p

// does this mean var keyword or var class??/o:p

}/o:p

}/o:p

 /o:p

I think it’s fairly easy to see that there’s no way to infer what thing1, myVar2 or myVar3 mean and indeed the C# spec forbids all 3 usages of var. This means in my example it’s safe for the compile to determine that in the case of thing1, myVar2 or myVar3 var is referring to the class that I’ve defined./o:p

 /o:p

Anyway, if even you don’t believe my explication of why var is like this, then please take one thing away form this explication: var can only be used for local variables. This is where the implications for anonymous types come in, because the only way anonymous types can be referred to is though the use of var this effectively means anonymous types cannot be passed in and out of a method./o:p

 /o:p

Okay sure, you can pass them in or out as System.Object, but then what use is that? A downcast to actual type can’t be preformed so you can’t see its properties. I think this might be a little unclear, so let’s see another example:/o:p

 /o:p

object Foo()/o:p

{/o:p

         return new {ProductID = 1, Name = “premier item”};/o:p

}/o:p

 /o:p

static void <?xml:namespace prefix = st1 ns = “urn:schemas-microsoft-com:office:smarttags” />Main/st1:place()/o:p

{/o:p

         object bar = Foo();/o:p

}/o:p

 /o:p

Foo is a method that returns an anonymous type, thought the use of System.Object, a reference to that value is placed in bar, but we can’t refer to either of our types properties because our reference is of type object. We can’t cast our object to the correct type, because we have no way to say its name, its real CLR name is made up by some compiler naming convention. Change bar type from object to var would not help here either because its type would still be inferred as object, as that is the return type of Foo()./o:p

 /o:p

Okay, so you’re thinking these limitations may make anonymous types look a bit week and un-useful? Well I think anonymous types have a couple of specific uses that make them very interesting. I think these limitations are also great, because it means they won’t be used willy-nilly to make code unreadable as some people complain about. So the specific use which I think they should be used for is as a mechanism to provide shape to some data which will then be shown to the user. I think this simple example shows just how powerful this is, we are able to select some data then select out just the bids we want to show in just a handful of lines:/o:p

 /o:p

        private void Form1_Load(object sender, EventArgs e)/o:p

        {/o:p

            var methods = typeof(string).GetMethods();/o:p

            var methodDetails = /o:p

                from m in methods/o:p

                where ! m.IsStatic/o:p

                orderby m.Name/o:p

                select new {/o:p

                    Name = m.Name, /o:p

                    CallingConvention = m.CallingConvention, /o:p

                    Abstract = m.IsAbstract,/o:p

                    Virtual = m.IsVirtual, /o:p

                    Public = m.IsPublic /o:p

                } ;/o:p

 /o:p

            BindingSource bindingSource = new BindingSource();/o:p

            bindingSource.DataSource = methodDetails;/o:p

            dataGridView1.DataSource = bindingSource;/o:p

        }/o:p

 /o:p

The full source for this demo is available here.

Feedback:

Feedback was imported from my only blog engine, it’s no longer possible to post feedback here.

re: C# 3.0 – The var “keyword” and anonymous classes - El Duderino

Because of implicit typing you can cast an object to the appropriate anonymous type.
I found this on another site:

public static T Cast<T>(object o, T type) where T : class
{
return o as T;
}

var person = Cast(ojb, new { Name = “”, Age = 0 });

re: C# 3.0 – The var “keyword” and anonymous classes - HaiL

The example is good.
Let me see a little for the var keyword and Linq to SQL.

The reuse of keywords in the C++ standard | keyongtech - http://www.keyongtech.com/4843446-the-reuse-of-keywords-in

The reuse of keywords in the C++ standard | keyongtech