0

Using VB.Net.

I have declared properties like these:

Private _name as String
Private _address as String


Public Property Name as String
   Get 
      Return _name
   End Get
   Set(value as String)
      _name = value
   End Set
End Property


 Public Property Address as String
   Get 
      Return _address
   End Get
   Set(value as String)
      _address= value
   End Set
End Property

I want to minimize declaring another variable that will handle the get and set. This variable or function will be used by all property and will handle all the get and set value of all properties.

For example:

Public Property Address as String
   Get 
      Return address /*Insert function here that can be use by all property*/
   End Get
   Set(value as String)
      address = value /*Insert function here that can be use by all property*/
   End Set
End Property

Thanks in advance.

shigatsu
  • 48
  • 8

2 Answers2

2

Yes, you can have property

  • without backing field
  • without set (readonly)
  • without get (insane write only property)
  • with different access modifier to get and set...

Sample in C#:

class Properties
{
   // Read-only, no backing field
   public int TheAnswer { get { return 42;}}

   // Write-only, no backing field
   public bool Destroyed { set { if (value) DestroyEverything();}}

   // No backing fields with some work in properties:
   int combined;
   public int Low { 
      get { return combined & 0xFF; }
      set { combined = combined & ~0xFF | (value & 0xFF); }
   }

   public int High { 
      get { return combined >> 8; }
      set { combined = combined & 0xFF | (value << 8); }
   }

   void DestroyEverything(){} 
}

VB.Net sample from MSDN - How to: Create a Property

Dim firstName, lastName As String 
Property fullName() As String 
    Get 
      If lastName = "" Then 
          Return firstName
      Else 
          Return firstName & " " & lastName
      End If 

    End Get 
    Set(ByVal Value As String)
        Dim space As Integer = Value.IndexOf(" ")
        If space < 0 Then
            firstName = Value
            lastName = "" 
        Else
            firstName = Value.Substring(0, space)
            lastName = Value.Substring(space + 1)
        End If 
    End Set 
End Property
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
0

In c# you can define properties in short format

public string Name{get; set;}

Compiler will create backing field for it and expand to simple getter and setter like

private string _name;

public string Name
{
    get { return _name; }
    set { _name = value; }
}

And of course you can provide or not access modifiers for both getter and setter shortcuts:

public string Name{ internal get; protected set;}
dmay
  • 1,340
  • 8
  • 23
  • I think question is about how to achieve that in VB.NET. (Question is not very clear though) – Prash Jul 30 '13 at 03:00