Translation of this C # code on VB.NET

I tried to translate the following c # code

public static class ObjectSetExtensions { public static void AddObjects<T>(this ObjectSet<T> objectSet, IEnumerable<T> objects) { foreach (var item in objects) { objectSet.AddObject(item); } } } 

for VB.NET:

 Module ObjectSetExtensions <System.Runtime.CompilerServices.Extension()> Public Sub AddObjects(Of T)(ByVal objectSet As ObjectSet(Of T), ByVal objects As IEnumerable(Of T)) For Each item In objects objectSet.AddObject(item) Next End Sub End Module 

But I get an error message:

An argument of type 'T' does not satisfy the 'Class' condition for a parameter of type 'TEntity'.

What am I missing?

+6
source share
4 answers

The C # version also does not compile for the same reason. It should be:

 public static void AddObjects<T>(this ObjectSet<T> objectSet, IEnumerable<T> objects) where T : class // Note this bit { foreach (var item in objects) { objectSet.AddObject(item); } } 

And the VB version:

 <Extension> _ Public Sub AddObjects(Of T As Class)(ByVal objectSet As ObjectSet(Of T), _ ByVal objects As IEnumerable(Of T)) Dim local As T For Each local In objects objectSet.AddObject(local) Next End Sub 

Note that in VB version, the restriction is part of the type parameter declaration. See MSDN for more information.

+11
source

It looks like you are missing the limitation:

 C#: where T : class VB: (Of T as class) 
+3
source

There is nothing wrong with your translation. This is the closest VB.NET equivalent of the provided C # code.

Based on a compilation error, although the ObjectSet type expects the type parameter to be limited to class . The original C # example does not have this, but if it was excluded from the question, the equivalent of VB.NET is as follows.

 Public Sub AddObjects(Of T As Class)(ByVal objectSet As ObjectSet(Of T) ... 
+1
source

Another conversion to VB.NET:

 Public NotInheritable Class ObjectSetExtensions Private Sub New() End Sub <System.Runtime.CompilerServices.Extension> _ Public Shared Sub AddObjects(Of T)(objectSet As ObjectSet(Of T), objects As IEnumerable(Of T)) For Each item As var In objects objectSet.AddObject(item) Next End Sub End Class 
0
source

Source: https://habr.com/ru/post/895192/


All Articles