0

I have created a read-only property(name) in class1. How can I use this name property in class2?

Public Class Class1
ReadOnly Property name() As String
    Get

        Return System.IO.path.GetFileName("C:\Demo\Sample1")

    End Get
End Property

Can I directly carry this name variable value into class2? Need suggestion.

Ram
  • 751
  • 5
  • 17
  • 26

3 Answers3

3

You can access this property everywhere where you have a reference to a Object of type Class1. So if your Class2 objects have a reference, they can use it.

For example:

Class Class2
    Property cls1 As New Class1

    Function getClass1Name() As String
        Return cls1.Name
    End Function
End Class

Another option is to make the property shared, because it's a value that is independent of any instance of Class1 that makes sense.

Then you can access it without an instance of Class1 via the class-name:

Class Class1
    Public Shared ReadOnly Property Name As String
        Get
            Return System.IO.Path.GetFileName("C:\Demo\Sample1")
        End Get
    End Property
End Class

Class Class2
    Function getClass1Name() As String
        Return Class1.Name
    End Function
End Class
Tim Schmelter
  • 411,418
  • 61
  • 614
  • 859
  • you have to admit Bala R posted that way before you did, regarding the shared property, and you edited it adding that, you should of mentioned his and +1 him. – JonH Jun 07 '11 at 15:23
  • @JonH: I would, but first i haven't seen that he was faster and second it seems that he has deleted his answer now. – Tim Schmelter Jun 07 '11 at 15:25
1

Your Readonly property is still an instance members and cannot be shared without instantiating Class1 and looking at the property definition, it can be Shared. You can make your property Shared and use it in class2

Public Class Class1
Shared Property name() As String
    Get

        Return System.IO.path.GetFileName("C:\Demo\Sample1")

    End Get
End Property

and in class2, you can call

Dim class1Name = Class1.name
Bala R
  • 101,930
  • 22
  • 186
  • 204
  • +1 not sure why you had deleted your original post you had it faster in and it was correct. – JonH Jun 07 '11 at 15:38
  • @JonH didn't seem like the OP was interested in having a Shared member but after seeing the discussion below, I thought I'd leave it out there for reference. – Bala R Jun 07 '11 at 15:40
0

Via an instance of Class1

    Public Class Class2

      Sub New()
            Dim o As New Class1
            Dim s As String  = o.Name

      End Sub

   End Class

Here is something to read on classes.

Saif Khan
  • 17,334
  • 28
  • 97
  • 144