|
|||||||||||||||||||||
|
|||||||||||||||||||||
|
Announcements
Chapters
Services
Feature Zones
|
new
IntroductionThe .NET framework 4.0 CTP has just been released and I think it’s a
good time to explore the new features of C# 4.0. In this post, I will
introduce about the following features: dynamic lookup, generics
covariance and contravariance support, optional and named parameters. Dynamic Lookup
If public static void Main() {
dynamic obj = “I’m statically System.String”;
obj.NotExistingMethod(“param”);
}
In the code, we create a string object and instead of assigning it to a variable of type private static void PrintID(dynamic obj) {
Console.WriteLine(obj.ID);
}
public static void Main() {
var person = new {ID = 111, Name = "Buu"};
PrintID(person);
var account = new {ID = 101, Bank = "Some Bank"};
PrintID(account);
}
We basically create two anonymous types, for the sake of convenience, both having a property called That example also implies an interesting usage of We are not just limited to make statically typed .NET objects become
dynamic, we can use this dynamic lookup feature to conveniently
interact with “actual” dynamic objects available through the Dynamic
Language Runtime (DLR) included in .NET framework 4.0. In fact, one can
implement such dynamic objects in C# by implementing the Some of you might wonder what code the compiler generates and whether there is any change to the CLR to support dynamic lookup or not. To answer that question, let’s look at the CIL generated from the very first code fragment of this post. (Click on the image to see the full size.)
The generated CIL is pretty verbose but a skim through it reveals
two important things. Firstly, our “dynamic variable” turns out to be a
plain old CLR object obj = "I'm statically System.String";
var payload = new CSharpCallPayload(
RuntimeBinder.GetInstance(),
false, false, "NotExistingMethod",
typeof(object), null);
var callSite = CallSite<Action<CallSite, object, string>>.Create(payLoad);
Action<CallSite, object, string> action = callSite.Target;
action.Invoke(callSite, obj, "param");
(In fact, I simplified the code a bit so that it can fit in one method, the actual CIL generated does have a check at So there’s really no magic behind the dynamic keyword. What the
compiler basically does is generating some payload containing the
information about the invocation so that it can be made at runtime. If
there’s any magic at all, it would be in the static method Now, we know that a “dynamic object” is actually a plain old object;
it should explain why method can accept dynamic parameters. It should
also be of no surprise to know that dynamic lookup can also be applied
to return value of an instance/static method or an instance/static
field. After all, unlike the var keyword which requires the compiler to
infer the exact type at compile time, the compiler in dynamic lookup
scenarios can simply pick Generics Covariance and Contravariance
In previous versions of C#, generic types are invariant. That is, for any two types To understand why pre-4.0 C# disallows covariance and contravariance, let’s look at some code var strList = new List<string>();
List<object> objList = strList; // compile-error, with cast or not
If the code in line 2, it can be error-prone. Consider what we can write after line 2 assuming it is allowed: // BOOM: we're adding an arbitrary AnyObject to what, at runtime, is a list of strings
objList.add(new AnyObject());
On the other hand, if C# supported contravariance, we could have written the following problematic code: var objList = new List<object>;
objList.add(3);
objList.add(new AnyObject());
List<string> strList = objList;
// BOOM: we're getting an arbitrary object thinking it’s a string
string element = strList.get(0);
Due to this invariant restriction, although for the good purpose, we
can’t easily reuse variables and methods to respectively get assigned
to or accepts various generic types. It’s somewhat unfortunately
because the key thing to realize that covariance is fine as long as Fortunately, C# 4.0 provides us an option: if a generics interface or generics delegate which has a reference type Let’s look at an example. We have a delegate T Generator<out T>();
Because this delegate does not take in any Generator<string> strGen = new Generator<string>(StringGenerator);
// Below line is compiled now because Generator<string> is
// subclass of Generator<object> under covariant rule
Generator<object> objGen = strGen;
// Downcast is also allowed for the same reason
strGen = (Generator<String>)objGen;
...
private string StringGenerator()
{
return "I'm a random string";
}
With contravariance, you need to use the delegate K Converter<in T, out K>(T param);
This converter takes an object of type var converter = new Converter<object, string>( ConvertImpl);
Converter<string, object> string2ObjectConverter = converter;
object result = string2ObjectConverter("A");
...
private string ConvertImpl(object o) {
return o.ToString();
}
Note that although the above examples show how to declare covariance and contravariance for delegate types, it’s not different to do so with interfaces. Before we finish with covariance and contravariance, let’s look at what code the compiler generates. After all, we know that the compiler must encode something to the CIL to denote covariant and/or contravariant generics types so that they can be consumed properly by client code. And this is what the definitions of our Generator and Converter delegates viewed from ildasm.
Do you notice anything? Those little minus and addition signs are used to denote contravariance and covariance respectively. And interesting enough, it turns out that the CLR has been supporting such CIL since the introduction of generics in .NET 2.0. Therefore, it’s possible to write CIL using covariance and contravariance under .NET 2.0+. Only by now that it’s possible to do so using C#. A final thought about this feature, while this is a good enhancement
to the language, I like the generics covariance/contravariance
implementation, enabled via wildcards, in Java better for its
flexibility. Anyway, let’s just be happy with it for now, we can’t have
everything. Optional and Named ParametersThe last two features of C# 4.0 that we’ll discuss about are optional parameters and named parameters. These features have been with VB.NET since forever and I’m glad they are finally implemented in C#. With optional parameters, we can provide default values for methods’ and constructors’ parameters. That way, we don’t have to write a bunch of overloaded methods and constructors. For example, we can define a constructor like this: public Cart(int id, String name = “default cart”, double amount = 0d) {…}
Now, you can invoke this constructor with any of these calls: new Cart(1);
new Cart(1, “my cart”);
new Cart(1, “my cart”, 105.5);
How exactly does C# implement this feature? If we look at the CIL generated for this code, we’ll see there’s no magic at all. Basically the default values will be injected to the call site so that the method invocation happens normally. Here’s the CIL generated by the compiler:
Some might think that the compiler gets the default values in the
source code to inject into the caller’s code. However, that will not
work if a method with optional parameters is published as a library. In
that case, there’s no way the compiler can get the default values to
inject to the code of the library’s client. Therefore, what the
compiler actually does is to encode the default parameters right into
the method itself. This is what the CIL for
Notice the While being a great feature, there’s a caveat when using optional parameters: since the compiler inlines the default values at the caller site, change to default values at the library site won’t be reflected unless the caller is recompiled. In order words, you should consider default values of parameters as part of the published API of a method and you’d better make them right the first time. Now, let’s say we want to call the To avoid ambiguity (for example when two optional parameters are both strings), C# won’t allow us to simply skip a parameter like this: new Cart(1, 15.5d); // compile-error
An approach C# could take is to allow this syntax: new Cart(1, , 15.5d);
However, this looks terrible enough with just one missing parameter,
much less more of them. (How do you like to read this code For this particular situation, named parameters are excellent solution: new Cart(1, amount: 15.5d);
This is not the only use of named parameters though. A very important purpose of named parameters is to enhance the readability of code. Let’s say you have a class having a bunch of fields that are to be initialized in a constructor. Without name parameters, a constructor of such class will look very ugly and hard to understand without resorting to the documentation, source code, or Intellisense. One approach is to create a builder to create instance of such class. For example: new BigClass.Builder().attr1(“value”).attr2(“value”)...attrN(“value”);
This will make the code more explicit about what values are to be assigned to what fields. However, the drawback is that we need to implement a builder class, which is quite a tedious task if we have to repeat that for many classes in our application. With C# 3.0, it’s not that bad because we can use object initializer to do something like this: new BigClass {Attr1 = “value”, Attr2 = “value”, …, AttrN = “value”}
This looks good, but we have to define all the necessary properties for it to work, which is also a tedious thing to do if we don’t really need properties for the class or if the class itself is immutable. With named parameters, we have a very nice solution without having to write any builder or property if we don’t want to. (Note the semicolon after the field name.) new BigClass{attr1: “value”, attr2: “value”, …, attrN: “value”);
// The below does the same thing
new BigClass{attrN: “value”, attr1: “value”, …, attr2: “value”);
Regarding the implementation of this at the CIL level, the compiler is smart enough to infer the correct argument order and simply perform a plain old method invocation.
ConclusionThat’s it. The key features of C# 4.0. I am personally glad that C# has come to support these. Some people said that C# has become so complex and started losing its original beauty. While I can understand that view, I think the situation is not that bad. While it’s obvious that C# has more and more constructs to supports functional and dynamic programming, the statically typed nature and the old constructs of the language are still there and no developer is forced to use the new features if they don’t need to. On the other hand, these features bring more options for those who need them and I’d rather have more options than to be handcuffed. | ||||||||||||||||||||