What is the advantage of using a generic-where-clause call with respect to a non-generic call?

I saw some examples when they transformed a call like

void Add(IDrawing item); 

in

 void Add<TDrawing>(TDrawing item) where TDrawing : IDrawing; 

Also, to convince intellisense to display the name of your class instead of the interface name when calling a function due to the use of the intended type in C # 4, is there any other advantage to using the second approach?

To answer Jon Skeet, the code our programmer uses is:

 public ObservableCollection<IDrawing> Items { get; private set; } public void Add<TDrawing>(TDrawing item) where TDrawing : IDrawing { this.Items.Add(item); } 

I see no advantage here in using the general, and not just using an IDrawing type IDrawing . I suppose there should be some case where it is very appropriate. I was curious to find out if something was missing.

+6
generics c #
source share
3 answers

It really depends on what happens elsewhere in the implementation. Here is another example:

 void Add<TDrawing>(TDrawing item, IList<TDrawing> list) where TDrawing : IDrawing { if (item.SomePropertyOfIDrawing) { list.Add(item); } } 

Now you would not want to use IList<IDrawing> here, because then you could not use it if you had List<Painting> for example ... whereas with the general version above it is absolutely normal for TDrawing be Painting : restriction ensures that the property is available for the if condition, and the fact that it is shared allows you to safely add an item to the list.

If you have complete examples in which you do not think there is an advantage, it would be advisable to present them specifically.

EDIT: No, in the exact example that is now given, there is no advantage in making it a general method.

+5
source share

Think about this scenario:

 void Add<TDrawing>(TDrawing item, Func<TDrawing, bool> func) { //implementation } 

Now, when you call this method at compile time, you will be able to access certain TDrawing specific TDrawing passed to this method for use with Func .

 Add<MyDrawing>(drawing, m => m.SomeMyDrawingProp); 
+1
source share

The semantics of the version with the where clause can be very different from the semantics when the struct is passed as a parameter. Storage locations (including parameters) of interface types contain references to heap objects. Forcing a structure that implements an interface to the storage location of this type of interface will create a new heap object with the same fields and methods as the structure, copy the entire contents of the field (public and private) to this new object, and then save a link to this object in storage. On the contrary, copying the structure to another storage of this type of structure will copy all the fields (public and private), but leave the result as a structure, and not a heap object.

0
source share

All Articles