Using ‘new’ in a projection?

I wish to project a collection from one type (Something) to another type (SomethingElse). Yes, this is a very open-eneded question, but which of the two options below do you prefer?

Creating a new instance using new:

var result = query.Select(something => new SomethingElse(something));

Using a factory:

var result = query.Select(something => SomethingElse.FromSomething(something));

When I think of a projection, I generally think of it as a conversion. Using new gives me this idea that I’m creating new objects during a conversion, which doesn’t feel right. Semantically, SomethingElse.FromSomething() most definitely fits better. Although, the second option does require addition code to setup a factory, which could become unnecessarily compulsive.

2

This question appears to be more about the appropriateness of using a factory method over a straight constructor call. My favorite example uses the TimeSpan type because it has several constructor overloads and several FromXXX static factory methods.

// how easily can you spot the bug?
int[] durationMs = { 1, 2, 3, 4 };

IEnumerable<TimeSpan> durations1 = 
    durationMs.Select(ms => new TimeSpan(0, 0, ms));

IEnumerable<TimeSpan> durations2 =
    durationMs.Select(ms => TimeSpan.FromSeconds(ms));

Which expression was the bug easier to spot in the two equivalent projections? Fixing the two expressions is also interesting:

// spot the bug after the fix?
IEnumerable<TimeSpan> durations1 = 
    durationMs.Select(ms => new TimeSpan(0, 0, 0, ms));

IEnumerable<TimeSpan> durations2 =
    durationMs.Select(ms => TimeSpan.FromMilliseconds(ms));

The durations2 expression is correct (bug fixed). However, adding just one 0 parameter to the durations1 constructor call was not enough – we have to add another 0 – going from the 3 parameter version to the 5 parameter version in order to specify milliseconds (as documented on msdn).

The “Framework Design Guidelines” book has some great advice on when to provide static factory methods. The book goes into more detail on each point whereas the link I provided merely summarizes the advice. Hope this helps.

1

In .NET Framework, the most frequently used convention is:

something.ToSomethingElse();

Examples:

  • 37.ToString();

  • new [] { "Hello", "World" }.ToArray();

  • DateTime.Now.ToBinary();

  • Guid.Empty.ToByteArray();

  • etc.

Note that depending on the context, maybe you could simply use Enumerable.Cast:

var result = query.Cast<SomethingElse>();

If you have a good reason to avoid this convention (for example if SomethingElse is a string), then use whatever convention you prefer from the ones you quoted in your question. They are both valid.


Another nice thing in C# is the implicit operator. For example, instead of:

var element = new XElement(new XName("section"), ...);

you simply write:

var element = new XElement("section"); // Uses implicit conversion from string to XName.

5

The problem with the second approach is that it requires a named (as opposed to an anonymous) type; otherwise, it would be impossible to pass something to a factory method. A large percentage of non-trivial LINQ queries use anonymous types, for example

query.Zip(otherQuery, (a, b) => new {First = a, Second = b}).Select(...)

or

query.Select((v,i)=> new {Value=v, Index=i}).Where(...).Select(...)

and so on. Having to define a named type for the anonymous type or using a generic Tuple<...> would solve the problem at the expense of readability.

Using new, on the other hand, lets you stay consistent even when you enter the territory of non-trivial LINQ queries. I would definitely recommend staying with new, and avoid making the matters that are already complex even more complex for no good reason.

If you want to change one type to another type but dont want to above code every time .. use automapper .It does these translation and more code reuse can be possible through it.

http://www.automapper.org/

let me know if you need highlight on same.

Personally I would either go with the first option if it’s only used in one place, or create an extension method if it is used in multiple places.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật