C# - Check which event changed / accessed a Property - c#

I have a class with property say
private string fieldSelectedItem;
public string FieldSelectedItem
{
get
{
return fieldSelectedItem;
}
set
{
fieldSelectedItem = value;
}
}
it is accessed from many place.
I came across a situation that the a property in class is accessed by some event. and also some event is changing the value. i tried debugging. is it possible to check which event/function has changed/accessed the property. is there any method to do so.

How about placing a breakpoint in the setter and looking at the stack trace.
Simples.

The stack trace should give you some information about where the call has come from, if you break in the property accessors.

Related

Can a property change without its setter getting called?

I have a simple property within a Model class with a getter and setter
private bool _isThresholdBreached;
public bool IsThresholdBreached
{
get
{
return _isThresholdBreached;
}
set
{
if(_isThresholdBreached == value)
return;
_isThresholdBreached = value;
OnThresholdBreached?.Invoke(this, new EventArgs());
}
}
Strangely enough the property's value is getting changed without the setter getter hit. I have put a breakpoint both within the getter and setter and I see that when the getter is called on successive occasions the value has changed but the setter breakpoint never hit. How is this even possible ? Any pointers please.
EDIT : I have verified and can confirm that the backing field is not modified anywhere else in the class except in the setter
Your property has a backing field.
Any code calling the field directly would update that value without calling the setter (this could be both direct or via reflection).
I would start with Find usages of the _isThresholdBreached followed by full text search in the solution.

Compare value member when setting property

I have a property, of a custom class, in C# that I have overridden the setter for. I want to compare a property of/in the custom class in the setter, like the following:
public DatabaseInfo CurrentDatabaseManagedSelection
{
get { return CurrentDatabaseManaged; }
set {
if (String.Equals(value.Name, CurrentDatabaseManaged.Name,StringComparison.OrdinalIgnoreCase))
return;
CurrentDatabaseManaged = DatabaseManagement.ReadDatabase(value.FileName);
}
}
Inside the DatabaseInfo class, there is a standard String property called Name.
However, when I run the program I get the following exception. Can anyone tell me why this happens and how to solve the issue please?
Exception has been thrown by the target of an invocation.
EDIT: I do set the value of the property which the setter above is for, in the constructor of the view model. I do this simply by setting CurrentDatabaseManagedSelection equal to an object of the DatabaseInfo class.
Think I might have found the problem... Well, I've solved it!
The issue was CurrentDatabaseManaged had not been initialized and so was equal to null when I tried setting the above property. I discovered this by adding a try.. catch in the setter method, and created a new String for CurrentDatabaseManaged.Name - the stack trace pointed to that line.
Hope that helps some one else in the future.

What is difference between this.PropertyName and _PropertyName?

as I often let LinqToSql generate partial entity classes, I am wondering if my practice of adding additional properties via code is correct and if there is a better way of doing the same thing? I am also wondering what is the difference between accessing the values of other properties using this.PROPERTY_NAME vs _PROPERTY_NAME?
In my web app I keep using this.PROPERTY_NAME, but I am wondering if that is, as I already said in opening sentence, the proper approach I should be using. Also, What is _PROPERTY_NAME and when do we use it?
Example:
public partial class User
{
public bool IsThisProper {
get{
return this.SomeIntProperty == 10; // I usually use this
}
}
public bool WhenToUseThisApproach {
get{
return _SomeIntProperty == 10; // What is this in comparison to above?
}
}
}
One is the property, and the other is the private backing field in which that property stores it's value. If you want to execute whatever code the property has in it's getter/setter, then use the property, if you don't, then don't. Chances are you want to use the property, not the field, especially with setting (setting it triggers the property changed event, so about the only time to use the property is if you don't want that event raised).

How to fix 'Remove property setter' build error?

I have a property in a model which has auto property getter and setter:
[DataMember]
public Collection<DTOObjects> CollectionName { get; set; }
I get the following error when building the solution:
Microsoft.Usage : Change 'propertyname' to be read-only by removing the property setter.
However, when I remove the setter and run the code, an error occurs because it's trying to set the property! It appears it's asking me to remove the setter despite the fact it is being set somewhere in the code.
Has anyone else come accross this problem? What do I need to modify?
I'm going to guess this is a list/collection (or something similar), in which case yes - it is unusual to have a setter. A typical example might be:
private readonly List<Foo> items = new List<Foo>();
public List<Foo> Items { get { return items; } }
Most callers should not be trying to assign to that; they shouldn't need to - they can add/remove/enumerate/clear/etc the list without ever needing to assign it.
an error occurs because it's trying to set the property
Then consider changing that code so that it doesn't try to set the property. It should not need to in virtually all cases.
One solution is to initialize the Collection in the constructor...
public class Email
{
public Email()
{
To = new List<MailAddress>();
}
....
public List<MailAddress> To { get; }
}
Then just use .add in code:
Email oEmail = new Email();
oEmail.To.Add(new MailAddress("Foo#fighter.com", "Mr. Foo"));
Just suppress it, right click the error and click suppress in code & an attribute will be added to the property.
Generally you shouldn't have a public set for collections as this allows the list to be replaced, however with objects that are created or deserialized at runtime sometimes the public setter is necessary.
From the docs:
"You can suppress the warning if the property is part of a Data Transfer Object (DTO) class. Otherwise, do not suppress warnings from this rule."
If it's not part of a DTO:
"To fix a violation of this rule, make the property read-only. If the design requires it, add methods to clear and repopulate the collection."
The preferred manner of replacing a read-only collection property is to use the Clear and AddRange methods (or their equivalents).
https://learn.microsoft.com/en-us/visualstudio/code-quality/ca2227?view=vs-2019

How do I specify a required attribute in a custom .NET Web control?

private string _itemId;
[Browsable(true),
Description("Required identifier for the Item.")]
public string ItemId
{
get { return _itemId; }
set
{
if (string.IsNullOrEmpty(_itemId))
{
_itemId = value;
}
}
}
How would I actually make that required when someone uses the control? I'm trying to find an attribute that says something like Required(true).
I don't know that there's an attribute for this. I believe on the Page_Load event (or perhaps some rendering event) just check if the value has been set. If not then throw an exception.
I don't think this is possible. Consider that the designer needs to be able to create an instance of the control when it's dragged from the toolbox. At that time, it's going to have default values for properties, and these values need to be valid.

Categories