I'm trying to fully understand the MVVM topic, and some of its methods. I have seen the method RaiseProperty()
in two different ways and I don't understand what the difference is.
This would be one:
public void RaiseProperty([CallerMemberName] string propertyName = "")
{
}
And the other directly does not have the [CallerMemberName]
.
I've been reading about it [CallerMemberName]
and it says it's to receive the name of the method that calls it.
And one of my doubts: Why know the name of the method that invokes it?
Then another thing that I don't quite understand is what is incorporated, in this case, by the method RaiseProperty
in my exercise:
public void RaiseProperty([CallerMemberName] string propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
What is it doing ?
, and what is it used for .Invoke()
?
Let's go point by point
As stated in the documentation, the CallerMemberName attribute allows you to avoid literal strings. To focus on the MVVM architecture, it is usual for a class to implement the interface
INotifyPropertyChanged
as follows:Where the method
RaiseProperty
is defined similar to the following:Well, what if you later want to change the name of the property, let's say instead of
Nombre
it beingNombreCompleto
. The change will not affect the literal strings as it happens inside the property setter , when the method is called:RaiseProperty("Nombre");
, resulting in the code not compiling. That is why the attribute is usedCallerMemberName
to avoid using string literals.However, the use of this attribute in the MVVM architecture is already somewhat obsolete since from version 6.0 of the C# language there is an operator
nameof
that allows obtaining the name of the variables, methods or types at compile time. Then, a more current implementation of the INotifyPropertyChanged interface would be something like:By referencing the property name instead of using a literal string, name changes are no longer an issue.
The symbol
?.
is the null conditional operator and is a syntactic sugar that is valid as of C# 6.0 to avoid comparing an object to the valuenull
and works like the ternary operator?:
. Suppose we haveA?.Metodo()
, if itA
is different fromnull
then the method is called, ie ,A.Metodo()
but if itA
isnull
then the result isnull
also.Focusing on the implementation of the method
RaiseProperty
, instead of doingthe null conditional operator is used:
PropertyChanged?.Invoke()
in such a way that the code is more compact and easier to understand (the latter is debatable). Finally, the methodInvoke
is a method that allows events to be fired, as in this particular case with the eventPropertyChanged
.