How to update Dependent Property when a property value changes? - c#

I have class that has two properties
public List<ChildMember> ChildMember
{
get
{
if (_ChildMember == null)
{
_ChildMember = this.UserRole == EUserRole.SalesExecutive ? this.GetMembers(this.LogonName, this.FilterByMID) : this.GetChildMembers();
}
return _ChildMember;
}
set
{
_ChildMember = value;
}
}
public int FilterByMID{ get; set; }
Essentially what I need to do is refresh the ChildMember list every time FilterByMID value is changed. I know I can set the this.ChildMember = null before updating the value of FilterByMID but I was wondering if this would be a good place to use INotifyPropertyChanged or perhaps a better way? Any help would be appreciated.
P.S.: GetMembers() method has the logic to check for 0s and -ve values in case it is bothering you :)
P.S.: This class lives in a class library but is used by ASP.NET WebApplication not WCF/WPF ... I noticed a lot of posts for WCF / WPF when I was searching for INotifyPropertyChanged so just wanted to clarify.

If you're only doing this once in this class I wouldn't mind bringing in INotifyPropertyChanged as you would have to make the notification in your setter for FilterByMID and then wire up an event handler in which you'd update the other property.
However, if you have multiple classes and instances needing to observe changes in properties on each other, it might be a more suitable way.
There're also some frameworks which are interesting in this regard. Some examples are the Reactive Extensions, Rx.NET, and the (built on the former) Reactive UI, which has a component not only suitable for user interface programming.

You should just clear the field in the FilterByMyID setter.
INotifyPropertyChanged allows you to notify someone else that a property changed.
Using it directly within your class will just make your code more complicated.

Related

INotifyPropertyChanged on all properties

Considering a class with a large number of properties, I want to implement a Dirty flag (in order to know if I should update the value in the database).
Is there any way to raise PropertyChanged on All the properties without having to manually go through and pluck it in the setter?
Edit to clear up some things: I did go through the thread that was linked here, and found some things, but unfortunately they do not suit my need. I don't really need to send an event, I just need to flip a flag. Also, that thread is quite old, and I hoped that maybe with C# 7 something came out which would help with it, that I missed in the changelog.
Why don't I just go and do it manually? Well, I might have to. But I'd have to declare the "hidden" variables, manage the code myself, I hoped MS would've done something to help, maybe something like was suggested in the other topic
public Type Name {get; set; notify { () => IsDirty = true; }}
that would help a lot (ignoring the fact it would ask me to declare the get and set anyways because they're abstract.
Add a method that looks like this:
public void Test()
{
if(PropertyChanged != null)
PropertyChanged(new PropertyChangedEventArgs(null));
}
Passing a null or empty string as the property name tells consumers that all properties have been changed.
https://msdn.microsoft.com/en-us/library/system.componentmodel.propertychangedeventargs.propertyname(v=vs.110).aspx
You can but its also a lot of work. Make an Attribute and use it on those properties. in the base class of your ViewModel,
which will implement INotifyPropertyChanged,
You register in its Constructor to the PropertyChanged event and check via reflection if the property that changed has your attribute on it,
and then set IsDirty accordingly.

Interface: Setter without a Getter

I came across an interface recently that only defined a setter like so:
public interface IAggregationView
{
DataTable SetSiteData { set; }
}
I queried this, and it is believed that this is one of the practices advocated by Microsoft for WebPart design (for SharePoint). In fact this example is directly copied from their examples.
I see this as a bad pattern, I don't see why someone should be able to set a value, and then not be able to read it again, and I believe a setter should always be accompanied with a getter (but not necessarily the other way around).
I'm wondering if anyone can explain the benefit of only having a setter, why Microsoft might be suggesting it in this case, and if it's really a good pattern to be following?
There are two scenarios I can see where this might be reasonable:
it is not possible get the value, for example a password; however, I would replace that with a void SetPassword(string) method, personally
the API it is designed for has no requirement to ever read the value, and it is being restricted purely to expose the minimum required API
Re my first point, a Set... method may not be ideal if the consuming API is essentially an automated mapper that assigns values to properties; in that scenario properties would indeed be preferable.
Re your "I don't see why someone should be able to set a value, and then not be able to read it again" - by the same point, however, it could be argued that someone setting the value already knows the value (they set it), so they have no requirement to do this.
But yes; it is very unusual to have a set-only property.
The role of get and set in interface properties is slightly different from those in classes.
public interface IAggregationView
{
DataTable SetSiteData { set; }
}
class AggregationViewImp : IAggregationView
{
public DataTable SetSiteData { get; set; } // perfectly OK
}
The interface specifies that the property should at least have a public setter. The definition and accessibility of the getter is left to the implementing class.
So if the interface contract only needs to write, get can be left open. No need to demand a public getter.
As a consequence, you cannot really specify a read-only property in interfaces either. Only 'at least read access'.
interface IFoo
{
int Id { get; }
}
class Foo : IFoo
{
public int Id { get; set; } // protected/private set is OK too
}
I can imagine using it for (manual) dependency injection. A class may need to have a collaborator injected that it only uses internally. Of course one would normally choose to do this in the class' constructor, but there may be times when one would wish to change the collaborator at runtime.
Classes that implement the interface may add a getter. Most uses of the property may be via an implementing class, not via the interface itself. In which case most code has the ability to get and set the property. The only reason for the interface may be that there is some common code that accesses a common subset of the methods/properties of a family of classes. That code only requires the setter, not the getter. The interface documents that fact.
An interface is just a facility for declaring a group of operations that are "atomically needed" (e.g. if you need to call method A, you'll need to read property B and set property C).
So as always, it depends.
In my experiences such interfaces crop up due to some special need, not for architectural reasons. For example in ASP.NET applications people sometimes make the Global.asax generated type derive from such an interface when they want to maintain global state. Someone might create an initialization value in a separate part of the application and need to publish it to a global place.
I usually like to replace a set-only property with a SetXxx method and make the method check that it is called at most once. That way I clearly enforce "initialization style" which is much less of a smell (imho).
Certainly one cannot set to never produce such a thing but it is to be avoided and will certainly raise questions during code review.

Is anything good/bad/unnecessary about this use of a public member?

Here is a synopsis of my code which is a moderately complex WinForms GUI.
The context of the dependencies is the model view presenter pattern.
public class StatSyncherFormView : Form, IView
{ ... }
public class Presenter
{
// Here is the member I made public
public readonly IView view;
public Presenter(IView view)
{
this.view = view;
}
}
static void Main()
{
IView view = new View();
Presenter presenter = new Presenter(view);
// Here is where I'm accessing the public member
Application.Run((Form)p.view);
}
1) I like the fact that view is only set by the constructor and won't be modified after. It makes me feel better in the context of multi threaded GUI development.
2) With public View {get; private set;} then I lose (immutability?).
3) With private readonly IView view I also need public View {get {return view;}} which feels (to me at least maybe someone can tell me otherwise) redundant.
My Question: I feel like (3) is the only way to avoid using a public member, but in this case I do not understand the benefit.
I realize this is minutiae, so Thanks in advance for anyone who takes the time to give me advice about this.
Just give the Presenter a Run() method.
This is really just a variant on the publicly-visible fields vs properties debate.
Following the standard guidelines (your option 3) is what most people will recommend, despite what you call "redundancy". BTW I'm not sure which of the following you mean by redundancy
a few extra characters to type, or
an extra getter method at runtime (which will probably be optimized away by the JITter).
In neither case is the "redundancy" significant.
Having said that, in your specific case Hans Passant's answer, which is to avoid the need for the property/field altogether, is probably the best.
The benefits of your third approach (which I like most) include:
You may add logic to the getter later without the need of recompiling calling code
Encapsulation: you have exactly one place in your code that gets the value from the actual field, allowing you to add logging or use any other debugging mechanism to troubleshoot unexpected behavior.
The encapsulation also means that you could actually change the field to hold some other type, as long as it can be converted to IView. This conversion can happen in the getter.
If you use public field, you cannot change it to property later without recompiling your assembly. So I think it is better to do it right at the first place by using property.

Binding a (complex) class property to CF.NET in C#

I am trying to make a 2-way binding of a class property.
public class MyClass{
public MyField AField1{get;set;};
public MyField AField2{get;set;};
}
public class MyField{
public string Value {get; set}
}
MyClass _class = MyClass();
_dv.DataSource = _class;
Databinding text object displays MyField class name instead of Value Property. I also tried to enter:
DataMember = "AField1.Value";
Is there any way to bind (2-way) AField1.Value of a class MyClass to a visual control?
It's a pain. There's no built-in way to achieve this in .NET, so I can safely say, even less in the CF.
You can get started with this article on MSDN Blogs, but it's pretty limited as you can only get one level of nested property bindings.
Personnally, I ended up writing a custom BindingSource, based on code that lies somewhere on the internets. I can't give you source code of my rewrite as it's property of my employer, but here's the link to the project that got me started.
There are a few drawbacks to the code provided : some of his namespaces are System.ComponentModel, and VS2010 didn't seem to like, so I had to rename them. And a few more issues in design time that can make it a pain to use (so you'll want to fix that too), like loosing the list of properties when you make a spelling mistake and so on...
But it's the best shot (IMHO) at creating a good BindingSource that handles nested objects, and you'll get the idea of what needs to be done to achieve your nested bindings.
The last drawback (and biggest probably, but I have no experience with CF) is that the project is written for the regular .NET Framework, so it's likely that you will have to rewrite it entirely.
Hope that helps....
Edit. Uh oh, I've been grave-digging without noticing... sorry.
PS. Another idea is to simply create one binding source for each of your nested objects, but it gets messy (IMO) if your object hierarchy is complex.

Class internal usage of public properties

Let's say I have a class that exposes one property. Is it considered to be a good aproach to use the private "holder variable" for internal use in the class? Or should I use the property for internal use also.
To explain, should I use:
public class foo
{
String _statusHolder;
public String myStaus
{
get { return _statusHolder; }
set{ _statusHolder = value; }
}
public void DisplayMyStatus()
{
Console.WriteLine(_statusHolder);
}
}
Or:
public class foo
{
String _statusHolder;
public String myStaus
{
get { return _statusHolder; }
set{ _statusHolder = value; }
}
public void DisplayMyStatus()
{
Console.WriteLine(myStaus);
}
}
I could see it as beeing more consistent and more readable to use the second approach. It would also be more effective if I would later do some modificatins in the set-statement. But are there any performance issues or is it considered bad-practise for some reason?
EDIT:
It seems that everybody is leaning towards using the property internally. My initial thoughts was the same, but as a novice programmer, you can never know.
Thanks everyone for the quick feedback!
Performance issues should be negligable, as the JITer or compiler will happily work out that your function call (the getter of the property) doesn't do anything exciting, and can be inlined.
The benefit is future changes to business logic that might be put in the getter, which your class will then automatically take advantage of, without refactoring too much.
Of course, the downside is, you might want to avoid that new business logic in some circumstances, so it is something that needs to be considered based on how likely a) logic will change, and b) that logic might need to be circumvented.
The other (potential) advantage of using the property internally is that you can easily move to, or from, automatic properties.
I tend to go with calling the properties cause once stuff gets tricky you can put in locking and business logic in the getter
For C# 3.0 I would go with something along these lines (and only explicitly create the backing field when its really needed)
public class foo
{
public String Status
{
get;
set;
}
public void DisplayMyStatus()
{
Console.WriteLine(Status);
}
}
Use the property if there is one. A property can have side effects like lazy initializing that you want to have regardless from where you access the variable.
Even if the property has no side effects now, other developers could add them later, and the places where the "raw" variable is used may be error-prone because the new code is not called.
And lastly, the property makes refactoring easier, for example, when the value later is no longer stored in a variable but is calculated inside the property accessor or comes from some other source variable.
Programming in Java, I prefer using the getter method because I can put a breakpoint there and/or see changes to it in logging output.

Categories