How to create an extension method for the type of a class in VB.NET

Asked

Viewed 99 times

1

I’m creating a MVC structure that will work similar to the Entity Framework within a VB.NET project where I created an attribute called TableAttribute which will define the table and the schemas to the model, thus:

Namespace Models.DataAnnotations
  <AttributeUsage(AttributeTargets.Class)>
  Public Class TableAttribute : Inherits Attribute

    Sub New(Name As String)
      Me.Name = Name
    End Sub

    Public Property Name As String
    Public Property Schema As String = "dbo"

  End Class
End Namespace

So I can add it to my models which will serve to make the application’s data layer:

Imports Models.DataAnnotations
Namespace Models
  <Table("Usuario", Schema:="Sistema")>
  Public Class UsuarioModel
    Public Property Id As Integer
    Public Property Login As String
    Public Property Senha As String
  End Class
End Namespace

Also, I have a Module that is related to Namespace.Modelsmaintaining a range of extension functions for models:

Imports System.Reflection
Namespace Models
  Public Module ModelsExtensions
    <Extension()>
    Function GetTable(Obj as Object) as String

      Dim type As Type = Obj.GetType()
      Dim temp As TableAttribute = type.GetCustomAttributes(GetType(TableAttribute), True)(0)

      If (temp IsNot Nothing) Then Return $"{temp.Schema}.{temp.Name}"

      Return $"dbo.{type.Name}"

    End Function
  End Module
End Namespace

My problem is that in order for me to get the name of any table, I’m obliged to instantiate it by making a new Usuario().GetTable().

Is there any way I can extend a method directly to the type Usuario? The result I hope would look like this: Usuario.GetTable()

1 answer

1


There is no way, after all extension methods are made to operate on top of an instance. If you don’t want to operate on an instance then there’s no point in doing it.

You probably just want a regular static method passing the type, or it should probably be a generic method, but I can’t say.

C# must have something similar to static extension method in version 8 or 9.

  • if it was a regular static method that I pass the type, how would I do it in VB.NET? in each class I would implement this?

  • No, it’s the same thing, only the guy would pass and not the instance.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.