1

When coding in Visual Basic, I'm able to define triggers to variables like: Whenever the value of the variable is changed, this triggers a function, which in turn changes the value of another variable. I wonder if there is a way to do the same in C#; that is, I want to define a trigger to a variable, fired every time when the value of that variable is changed.

Below code is how I do it in VB. When running this App, whenever a new user logs in, the App assigns the username like ActiveUserName = "SomeUserName", and this in turn automatically updates the FormMain.StatusLabelUserName.Text in the form. So, is there a way to achieve this trigger in C#?

Public Property ActiveUserName() As String
    Get
        ActiveUserName = FormMain.StatusLabelUserName.Text
    End Get
    Set(ByVal Value As String)
        FormMain.StatusLabelUserName.Text = Value
    End Set
End Property
ssd
  • 2,340
  • 5
  • 19
  • 37

6 Answers6

2

I believe you're looking for Properties

private int localMember;
public int publicProperty
{
  get
  {
    return localMember;
  }
  set
  {
    localMember = value;
    //Do whatever you want here.
  }
}

The "get" block is run any time you access the value. The "set" block is run any time you assign a value.

MikeH
  • 4,242
  • 1
  • 17
  • 32
  • Just a quick addition; the feature the OP wants can be accomplished by raising and event inside the setter; which the framework registers for with a binding (WPF only of course). – BradleyDotNET Nov 04 '14 at 23:06
  • 1
    BTW, `value` is a special keyword for use in the set block. It contains the assigned value. – MikeH Nov 04 '14 at 23:10
1

This is handled by raising events. This post describes how to do it well.

Community
  • 1
  • 1
mobiusklein
  • 1,403
  • 9
  • 12
1

This is a simple property. Here's the C# syntax:

public string ActiveUserName
{
    get { return FormMain.StatusLabelUserName.Text; }
    set { FormMain.StatusLabelUserName.Text = value; }
}
Lucas Trzesniewski
  • 50,214
  • 11
  • 107
  • 158
1

Properties can work the same in C#

public string ActiveUserName
{
  get{ return FormMain.StatusLabelUserName.Text;}
  set{FormMain.StatusLabelUserName.Text = value; /*do more stuff here; */}
}

This can get rather messy and somewhat rigid however. You may consider using events to accomplish the same thing.

crthompson
  • 15,653
  • 6
  • 58
  • 80
0

Use INotifyPropertyChanged event.

rp4361
  • 433
  • 1
  • 5
  • 20
-1

Properties and the set brackets. INotifyPropertyChanged could be implemented for WPF databindings for exemple.

Alador
  • 1