Home > C#, .NET

Some of the new things in C# and .NET 4.0

29. September 2009

Just thought I should share some thoughts and information about some of the new things that I think are a bit interesting. This is in no way a complete list of new things.

Language

 

Optional and named arguments

I feel VB6 coming back to me when I see this and I guess that this is something the VB.NET people already have? Optional arguments simply let’s you omit argument values and named arguments let’s you enter them in any order you’d like.

public int Test(int a, int b = 1, int c = 2, int d = 3) {
return a + b + c + d;
}

public string Hello(string name = "World") {
return "Hello, " + name + "!";
}

public void Main() {
Test(0); //Test(0,1,2,3)

Test(0, c: 5); //Test(0,1,5,3)

Test(d: 5, a: 0); //Test(0,1,2,5)

Hello(); //Hello("World");
}

I think this is something I will use for saving some lines of code where I earlier wrote several method/constructor overloads.

Note that both functions will work not only in methods but also in constructors and indexers.

Variance

Oh dear… Let’s see if I can make this one justice.

Everybody knows that you can write this:

//No problem!
string s = "Hello";
object o = s;

It works because string is a subclass of System.Object and you can always cast to a less derived object.

The following however does not work.

IList<string> strings = new List<string>();
IList<object> objects = strings;
// And if you think of if it kind of makes sense:
objects[0] = 1000.0;
var whatAmI = strings[0]; //Would contain a string representation of 1000.0

The thing is that the above code should be fine if the collection objects where “readonly”, say, IEnumerable<T> but in C# pre 4.0 you wouldn’t have any luck there either. But now!

//Will work in C# 4.0 since IEnumerable is a readonly collection
IEnumerable<string> strings = new List<string>();
IEnumerable<object> objects = strings;

Let’s try and make a “real” example. The following code will not compile in C# 3.0 but in 4.0 it’s party time. The reason is the last line of code. Only with C# 4.0 is it possible to cast apples and bananas to IEnumerable<Fruit>.

public class Fruit { }
public class Apple : Fruit { }
public class Banana : Fruit { }

public class Varicance
{
public static void Main()
{
//Bag of apples
var apples = new List<Apple>() {
new Apple(),
new Apple()
};

//Bag of bananas
var bananas = new List<Banana>() {
new Banana(),
new Banana()
};

//Let's put them together
IList<Fruit> fruitBasket = apples.AsEnumerable<Fruit>()
.Concat(bananas).ToList();
}
}

For a deeper explanation of variance I recommend watching the following video with Anders Hejlsberg. Expert to Expert: Erik Meijer and Anders Hejlsberg - The Future of C#

Dynamic

This is probably one of the biggest news in C# 4.0 and it’s also the one I will write least about. But this is what it is:

C# 4.0 introduces a new static type called dynamic and if you declare an object dynamic the properties and methods of that objects won’t be resolved until runtime. This is useful when communicating with other dynamic languages and COM objects.

Framework

 

Code Contracts

This is a way for you to more easily declare and visualize the contracts that a method must fulfill. Not only is it more easy for you as a developer to understand what the “rules” for a method is the compiler can also pre-check the conditions and find code that will break your contracts.

public object GetObject(string id)
{
Contract.Requires(!string.IsNullOrEmpty(id));
Contract.Ensures(Contract.Result<object>() != null);

return Repository.Get(id);
}

The contract will ensure that the id argument is not null or empty and also that the returned object is not null.

Parallel Extensions

Quite a lot of work has been done to add better multi core support to .NET, better as in easier to use. There is a improved ThreadPool, two new types: Task and Task<T> that you can think of as a lighter, easier to use Thread type and Parallel LINQ(PLINQ).

public void PLINQ()
{
//.AsParallel is all you need...
var data = GetData();
var q = from x in data.AsParallel()
where someFunc1(x)
orderby x.SomePropery
select x;
}

BigInteger

For when you need does reeeally big numbers… In theory the BigInteger has no maximum but eventually you will run out of memory.

//1e+100. One followed by one hundred zeros.
BigInteger googol = BigInteger.Parse("10000000000000000000000000" +
"0000000000000000000000000" +
"0000000000000000000000000" +
"0000000000000000000000000");

//(1e+100)^1000. That's one followed by 100 000 zeros!!
//(That is 27 pages in Word with nothing but zeros....)
BigInteger reallyBig = BigInteger.Pow(googol, 1000);

Better file system enumerations

The GetFiles and GetDirectories methods on System.IO.Directory and DirectoryInfo returns an array of objects. This is not always(when would it be?) ideal. A better solution would be if they returned IEnumerables and that the internally used yield return. And now they do! Or at least the new EnumerateXXXX methods do. This is far more efficient when writing code like this.

public FileInfo FindFile(string filename)
{
var directory = new DirectoryInfo(SOME_PATH);
foreach (var file in directory.EnumerateFiles())
if (file.Name.Equals(filename, StringComparison.InvariantCultureIgnoreCase))
return file;
}

There you go. Is I said, this is only a handful of the new things in C# and .NET 4.0 but it’s some of the coolest ;)

C#, .NET ,

Comments

2/20/2010 3:10:45 AM #
I've been here a couple times and it seems like your articles get more informative every time. Keep it up I enjoy reading them.
2/20/2010 10:24:18 AM #
Have you thought about adding some sort of bookmarking buttons or links to your website?
2/21/2010 3:17:01 AM #
Definitely agree with what you stated. Your explanation was certainly the easiest to understand. I tell you, I usually get irked when folks discuss issues that they plainly do not know about. You managed to hit the nail right on the head and explained out everything without complication. Maybe, people can take a signal. Will likely be back to get more. Thanks
2/21/2010 9:38:57 AM #
Great Post, I love to read articles that are informative and beneficial in nature. Thank you for sharing your experiences and I look forward to seeing more.
2/21/2010 10:10:30 PM #
Can I quote you on my website if I link back to your website?
2/24/2010 1:15:52 PM #
If you are looking for information on fishing in Key West or Key West fishing guides, check out this site- http://www.keywestcustomcharters.com Tight lines!
2/26/2010 8:06:50 PM #
I'm so glad to have found your web page. My pal mentioned it to me before, yet never got around to checking it out until now. I must express, I'm floored. I really enjoyed reading through your posts and will absolutely be back to get more.
2/27/2010 8:14:23 AM #
Should I get a Virtual Private Server? Currently I am using shared hosting but they keep disabling my account due to high server load. Im getting about 3,000 unique views a day. What brand should I get?
3/1/2010 5:20:46 AM #
Need a quit smoking program http://stop-smokingprograms.com  Take a look!  Stop smoking and kick the habit.
3/2/2010 2:02:20 AM #
Finally someone that actually knows what they are talking about - thank you!
3/2/2010 6:54:46 AM #
There is more to life than increasing its speed.
3/3/2010 5:07:19 AM #
WoW Mobiles is awesome! I get free mobile service with t-mobile because I refered 3 people to wow. You can too!
3/3/2010 2:57:55 PM #
I like streaming movies online, it is way cheaper than going to the theaters.
3/4/2010 4:50:02 PM #
I like watching movies online, it is way cheaper than going to the theaters.
3/5/2010 6:09:05 AM #
I believe that templates are a nice means to resolve a kind of problem: Doing stuff in real-time when it could be done in compile-time. Why? To have the code lighter and simpler to manage – and it’s rather OK. But this sort of meta-programming lets you write code +- ‘naturally’ and have the overhead cut by the compiler.
3/5/2010 3:01:13 PM #
Is tethering against the Terms of Service of mobile phone providers? Which ones allow it?
3/5/2010 5:51:45 PM #
This is certainly my initial stop by and I really like what I'm seeing. Your weblog is so much fun to look over, quite compelling as well as informative. I'll undoubtedly recommend it to my friends. Nevertheless, I did have some problem with the commenting. It kept giving me an problem whenever I clicked on publish comment. I hope, that can be fixed. Many thanks
ELC
3/6/2010 9:42:12 AM #
I wanted to thank you for this interesting I definitely loved every little bit of it. I have you bookmarked your site to check out the latest stuff you post.
3/7/2010 4:36:53 AM #
Perfect reports & Great a site….
3/8/2010 9:40:08 PM #
Hi. Very nice Blog. Not really what i have searched over Google, but thanks for the information.
3/9/2010 3:59:23 AM #
Do you know which mobile phone services allow tethering?
3/9/2010 5:26:30 AM #
amazing stuff thanx
3/9/2010 1:27:04 PM #
I can see that you are an expert at your field! I am launching a website in the near future, and your information will be very handy for me. Thanks for all your input. With best wishes x
3/9/2010 5:38:44 PM #
This is a great post, but I was wondering how do I suscribe to the RSS feed?

Add comment


(Will show your Gravatar icon)

  Country flag

biuquote
  • Comment
  • Preview
Loading



Clicky Web Analytics