Home > Back-end >  how to get the anonymous backing field name of an auto-implemented properties
how to get the anonymous backing field name of an auto-implemented properties

Time:09-18

Not a full expert in C# here. Sorry in advance if this is a very common question.

consider the following property.

public bool IsOn{ get;set; }

above getter/setter property has anonymous backing field according to https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/auto-implemented-properties

Is there a way for me to see what this "anonymous backing field" name is so that I can expand the setter without adding extra code. All I want to do is log the content of the values that's getting set to in a dll where this code exist. For example,

public bool IsOn
{ 
   get;
   set
   {
      Log(value);
      "field name generated by c#" = value;
   }
}

Or do I have to create a field manually every time I want to see what the value is being set to? if so it seems like a very unproductive approach to have them used when we consider about usability. Mind you this is only one of the setters I want to log out. there are many more needs logging on this specific dll

CodePudding user response:

An Auto-Implemented Property is a property that has the default get- and set-accessors. If you have to add logic to them, you have to create a usual property with a backing field:

private bool _IsOn;

public bool IsOn
{ 
   get { return _IsOn; }
   set
   {
      Log(value);
      _IsOn = value;
   }
}

However, a property that is logging somewhere is not a real property anymore, that's a heavy side-effect in my opinion. I would make it a method:

private bool _isActive = false;

public void ChangeState(bool active)
{
      Log(active);
    _isActive = active;
}

public bool IsActivated => _isActive;
  •  Tags:  
  • c#
  • Related