Usually when I need to create a copy of some primitive type collection based on List<T> usually I use overload constructor of List class such as List<T>(IEnumerable<T>). It basically creates a new List<T> collection and populates the items based on IEnumerable<T> input parameter. Copied version is isolated from the original one which means changes made in copied version will not effect the original one.
Recently I had the same task but instead of List<T> I had to use Collection<T> and it was required to make a deep copy of that collection. I was expecting that constructor Collection<T>(IList<T>) will do the same what List<T> does and will return me a new instance of Collection<T> object isolated from the original one.
For my big surprise it didn’t. It actually wraps the original collection. So, those two collections are coupled to each other. As soon as you make a changes in the “copied” version the original collection will be effected as well.
This is a small example which illustrates it:
So, be careful when you need to make a Deep Copy of collection.
Technorati tags:
.Net,
C#
Previous materials of C# 3.0 Feature series:
"Dynamic" Classes
Anonymous Type is basically the C# way how we can dynamically create, populate and use a class without type declaration. If for some reason we need temporary classes as data carrier without any business logic implementation then Anonymous Types could be the perfect solution. Instead of having statically declared bunch of standard classes we can eliminate our efforts and use Anonymous types. Actually this feature mainly was created to support Expression Tree and LINQ which would be hard to implement without it.
Anonymous type declaration syntax is very simple.
1: var someObject = new {Name = "Bob", Age = 23};
As you can see we used three technics introduced by C# 3.0 features: Auto Property, new Object initialization syntax and var keyword. Without any of them it won’t be possible to have Anonymous Types in game.
How does it work?
Actually Anonymous Type is not such “anonymous” like it sounds. What actually happens is that during the compilation compiler creates “static” type for us.
If we compile the application and look at the compiled IL code then we will find some strange f_AnonymousType0’2 class.

This is our Anonymous Type introduced by compiler which actually under the hood creates type with public properties.

Usage
After declaration of object based on Anonymous Type we are free to use it in a standard way as we do with standard classes including intellisense support.

1: var someObject = new {Name = "Bob", Age = 23}; 2: Console.WriteLine("Name is {0}, age is {1}", someObject.Name, someObject.Age);
Previous materials of C# 3.0 Feature series:
“var” keyword
During the local variable declaration we have to explicitly specify the type even if the variable doesn’t have any value yet. The “var” expression brings as ability do not specify the type during local variable declaration. The compiler will get it from the initializer.
Let’s declare two local variables of the same type (User) but one will be declared in standard (old) way and another one with using “var” keyword.
1: User userTodd = new User() { UserName = "Todd" }; 2:
3: var userBob = new User() {UserName = "Bob"};
Disassembler shows that both variables (userTodd and userBob) have the same type CSharp30Features.User even we did not explicitly specify the type in case of userBob variable.

Also keep in mind that ones the variable has been initialized by one type it won’t be possible to reassign it to another type. We will get compile time error:
1: var someVar = 1;
2: someVar = "This assignment will bring compile time error";
Why to use “var” keyword?
The obvious question is what is the advantage of using “var” keyword.
Redundancy in expression
We do not need to specify type twice in local variable declaration expression.
1: SomeType varName = new SomeType();
The right side of the expression already shows which type variable will be. It is enough to specify it just ones:
1: var varName = new SomeType();
Anonymous Types support.
“var” expression became necessarily after introducing the Anonymous Types. In case of Anonymous Type declaration we cannot use standard expression as the type which variable has to be assign to is unknown.
1: ??? someVar = new {Property1="value", Property2="Another value"};
This is a valid expression for Anonymous Types:
1: var someVar = new {Property1="value", Property2="Another value"};
I am planning to speak explicitly about Anonymous Types in my next upcoming blog post “C# 3.0 Features. Part IV: Anonymous Types”
Technorati tags:
.Net,
C# 3.0,
Var
Previous materials of C# 3.0 Feature series:
Object Initialization
New object initialization technique gives us ability to define and fill the public property of the object on the fly. This expression was created to support LINQ but it can be used anywhere. This expression helps to fill values during the initialization and keep constructor empty.
1: public enum Sex { Male, Female }
2:
3: public class User
4: {
5: public int UserId { get; private set; }
6: public string UserName { get; set; }
7: public string UserAddress { get; set; }
8: public DateTime DateOfBirth { get; set; }
9: public Sex UserSex { get; set; }
10: }
User object initialization by using OLD style expression:
1: User user = new User();
2: user.UserAddress = "FR, Paris";
3: user.DateOfBirth = new DateTime(1984, 1, 1);
4: user.UserName = "Michelle";
5: user.UserSex = Sex.Female;
Similar object initialization by using new feature:
1: User user = new User
2: {
3: UserAddress = "US,Redmond",
4: DateOfBirth = new DateTime(1974, 1, 1),
5: UserName = "Mike",
6: UserSex = Sex.Male
7: };
Collection Initialization
There is a similar feature for collection initialization. We can define a collection and add object on the fly.
The standard way of collection initialization:
1: List<User> users = new List<User>();
2: users.Add(user1);
3: users.Add(user2);
Initialization of collection by using new C# 3.0 feature:
1: List<User> users = new List<User>{user1, user2};
Both in one
Finally we can combine those two expressions and have the whole collection initialization in one line. This could be helpful when preparing collection with dummy data for testing.
1: List<User> users = new List<User>
2: {
3: new User
4: {
5: UserAddress = "US,Redmond",
6: DateOfBirth = new DateTime(1974, 1, 1),
7: UserName = "Mike",
8: UserSex = Sex.Male
9: },
10: new User
11: {
12: UserAddress = "US, New-York",
13: DateOfBirth = new DateTime(1978, 1, 1),
14: UserName = "David",
15: UserSex = Sex.Male
16: }
17: };
I would like to continue my blogging experience with a series of blog posts related to C# 3.0 features. Although there are already a lot of materials regarding this subject in .Net community my impression is so strong that it forces me write about it.
I decided to post simple blog per feature. The first one in the list is “Auto Property”
Redundancy in Property Declaration
Usually, we use properties as data carrier which do not contain any business logic inside. This especially visible on DTO class implementation. For every property in the class we have to introduce private field which connects to property in getter and/or setter without being used in other parts of the class.
1: public class User
2: {
3: private int _userId;
4: public int UserId
5: {
6: get { return _userId; }
7: set { _userId = value; }
8: }
9:
10: private string _userName;
11: public string UserName
12: {
13: get { return _userName; }
14: set { _userName = value; }
15: }
16:
17: }
As you can see we face to redundancy in property declaration.
Simplify Property Declaration
By using Auto Property feature of C# 3.0 we can declare a property without private field declaration, with empty setter and getter (using the same style as we do in interfaces). The compiler will create an appropriate code for us. It will create a private field and use it in set_ get_ methods accordingly.
On the example below the UserId property has been converted to Auto Property declaration style where UserName remained the same.
1: public class User
2: {
3: public int UserId { get; set; }
4:
5: private string _userName;
6: public string UserName
7: {
8: get { return _userName; }
9: set { _userName = value; }
10: }
11: }
We will compile the code and explore the result. IL Disassembler shows that compiler created both "get_XXX" and "set_XXX" methods for UserId property the same way as it did for UserName.
Advantage
The advantage of this feature is obvious:
- Saves time during class declaration
- Removes redundancy in the code
- Code becomes much more clear and readable
1: public class User
2: {
3: public int UserId { get; set; }
4: public string UserName { get; set; }
5: }
BTW, we still can play with access modifiers of getter and setter if needed:
1: public class User
2: {
3: public int UserId { get; private set; }
4: public string UserName { get; internal set; }
5: }
Attention
Auto property applies only on public properties which private member is not used in other part of the class (including constructor).
Technorati tags:
C# 3.0,
.Net 3.5