How to create property for an Array? VB.NET

Asked

Viewed 239 times

1

I have a question in Arrays, I do not know if I wrote right if what I am referring is really a property, I will explain in detail what I want to do.

For example:

I want to create an array with several names =

dim nomes() as string

After that wanted to make a property as for example

nomes(0).middleName
nomes(0).FullName

Is that possible? How do I create these properties?

1 answer

1

It’s not possible. The most you can do is create a class for it.

Something like

Imports System
Imports System.Collections
Imports System.Collections.Generic

Public Class Program
    Public Shared Sub Main()

        dim names As New List(Of Names)


        names.Add(New Names("Joaquim"))
        names.Add(New Names("Pedro", "Moraes"))

        names(0).LastName = "Barbosa"

        Console.WriteLine(names(0).FullName)
        Console.WriteLine(names(1).FullName)
    End Sub
End Class

Class Names

    Sub New(ByVal first As String)
        Me.m_FirstName = first
    End Sub

    Sub New(ByVal first As String, ByVal last As String)
        Me.m_FirstName = first
        Me.m_LastName = last
    End Sub


    Public Property FirstName() As String
        Get
            Return m_FirstName
        End Get
        Set
            m_FirstName = Value
        End Set
    End Property
    Private m_FirstName As String
    Public Property LastName() As String
        Get
            Return m_LastName
        End Get
        Set
            m_LastName = Value
        End Set
    End Property
    Private m_LastName As String
    Public ReadOnly Property FullName() As String
        Get
            Return Convert.ToString(FirstName & Convert.ToString(" ")) & LastName
        End Get
    End Property
End Class

See working on . NET Fiddle.

Since I don’t program VB.NET, there may be some better way to organize this example code. Anyway, the idea is this, create a class and modify the properties of this class.

Here is also an example in C#.

using System;

public class Program
{
    public static void Main()
    {
        var nomes = new Names[2]; 
        nomes[0] = new Names {  FirstName = "Pedro" };
        nomes[1] = new Names {  FirstName = "Joaquim", LastName = "Soares" } ;          
        nomes[0].LastName = "Barbosa";

        Console.WriteLine(nomes[0].FullName);
        Console.WriteLine(nomes[1].FullName);
    }
}

class Names
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string FullName { get {return FirstName + " " + LastName; } }
}

See working on . NET Fiddle.

Browser other questions tagged

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