Extend a Function without extension method

Harald Bacik 61 Reputation points
2020-12-29T14:56:07.743+00:00

Hey

The title is a bit curious...

What I try to achieve is as follows:

I have a class with a function something like this:

 Public Class Test
       Public Function GetName As String
          Return "Jane Doe"
       End Function
    End Class

Now I would like to have an 'extension' to the string.
But not an extensio module, which does extend the string. - Because this would work for every string (what is not right)
And I must Import the extension. - What I also want to avoid.
So, what I want to be able:

Dim locTest As New Test
Console.WriteLine(locTest.GetName)
-- Result: Jane Doe
-- What I want to achieve

Console.WriteLine(locTest.GetName.Firstname)
-- Result: Jane

Console.WriteLine(locTest.GetName.Lastname)
--Result: Doe

All these 3 things should work.

What I tried is to use an Interface as return type, which returns the Firstname and Lastname, but it isn't working, because then the .GetName isn't working as string

Hope someone could give me advise to this

THX

VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,724 questions
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 117.2K Reputation points
    2020-12-29T15:55:25.867+00:00

    Try something like this:

    Public Class FullName
        Public Property FirstName As String
        Public Property LastName As String
    
        Public Overloads Function ToString() As String
            Return $"{FirstName} {LastName}"
        End Function
    
        Public Shared Widening Operator CType(n As FullName) As String
            Return n.ToString
        End Operator
    End Class
    
    Public Class Test
    
        Private Property Name As FullName
    
        Public Sub New(firstName As String, lastName As String)
            Me.Name = New FullName With {.FirstName = firstName, .LastName = lastName}
        End Sub
    
        Public Function GetName() As FullName
            Return Name
        End Function
    End Class
    
    . . .
    
    Dim locTest As New Test("Jane", "Doe")
    Console.WriteLine(locTest.GetName)
    Dim name As String = locTest.GetName
    ' Result: Jane Doe
    
    Console.WriteLine(locTest.GetName.FirstName)
    ' Result: Jane
    
    Console.WriteLine(locTest.GetName.LastName)
    ' Result: Doe
    

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.