Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Translation of this C# code to VB.NET

I tried to translate 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);
         }
    }
}

to 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 getting an error that says:

Type argument 'T' does not satisfy the 'Class' constraint for type parameter 'TEntity'.

What am I missing?

like image 706
JAS Avatar asked Aug 16 '11 20:08

JAS


People also ask

What is translation in C?

In C and C++ programming language terminology, a translation unit (or more casually a compilation unit) is the ultimate input to a C or C++ compiler from which an object file is generated.

What are translation units in C++?

A translation unit consists of an implementation file and all the headers that it includes directly or indirectly. Implementation files typically have a file extension of . cpp or . cxx .

What is translate in CS?

A translator is a program that converts source code into object code. Generally, there are three types of translator: compilers. interpreters.


2 Answers

The C# version doesn't compile either, 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 is:

<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 how in the VB version the constraint is part of the type parameter declaration. For more details, see MSDN.

like image 187
Jon Skeet Avatar answered Sep 21 '22 01:09

Jon Skeet


It sounds like you are missing a constraint:

C#:
   where T : class

VB:
   (Of T as class)
like image 45
Tejs Avatar answered Sep 21 '22 01:09

Tejs