Search code examples
c#.netvb.netsyntaxcode-translation

Translate simple code with C#6 syntax to Vb.Net


Someone could help me to translate this simple snippet that uses the new C# 6 syntax, to Vb.Net?

The resulting LINQ query is incomplete (wrong syntax) when doing a translation in some online services like one from Telerik.

/// <summary>
///     An XElement extension method that removes all namespaces described by @this.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>An XElement.</returns>
public static XElement RemoveAllNamespaces(this XElement @this)
{
    return new XElement(@this.Name.LocalName,
        (from n in @this.Nodes()
            select ((n is XElement) ? RemoveAllNamespaces(n as XElement) : n)),
        (@this.HasAttributes) ? (from a in @this.Attributes() select a) : null);
}

Solution

  • Give this a shot:

    <System.Runtime.CompilerServices.Extension()> _
    Public Function RemoveAllNamespaces(this As XElement) As XElement
        Return New XElement(this.Name.LocalName,
            (From n In this.Nodes
             Select (If(TypeOf n Is XElement, TryCast(n, XElement).RemoveAllNamespaces(), n))),
            If((this.HasAttributes), (From a In this.Attributes Select a), Nothing))
    End Function
    

    In case you'll be converting other code, here's the steps I took:

    • Added the Extension attribute, because VB does not have syntax like C# does for creating extension methods.
    • Replaced the C# ternary operator with VB If(condition, true, false).
    • Replaced C# casts with VB TryCast(object, type).
    • Replaced C# type checking with VB TypeOf object Is type.
    • Replaced C# null with VB Nothing.