From the course: Advanced C#: Functional Programming Patterns
Unlock this course with a free trial
Join today to access over 24,500 courses taught by industry experts.
What about impure class properties - C# Tutorial
From the course: Advanced C#: Functional Programming Patterns
What about impure class properties
.NET types have methods, but they can also support other members like events, operators, and properties. Just like methods, these members can alter the internal state of an object, leading to side effects. In this video, I'm looking at properties. In functional programming, properties that introduce side effects are generally discouraged because they violate immutability, predictability, and referential transparency. Simple properties implemented with C#'s auto-properties are typically fine. However, the preferred approach is to make the type immutable. If your type isn't immutable and you write custom code in a properties getter or setter, it's important to check if that code is causing any unintended side effects. Here's an example. I have this class called SimpleColor and it's for creating colors from red, green, and blue values. So here you can see I've got these mutable backing fields via properties. I've got red, green, and blue. I've got a constructor here on line 13 that I use…
Contents
-
-
-
-
(Locked)
Function categories3m 18s
-
(Locked)
Write pure functions for better code3m 52s
-
(Locked)
Example of an impure function1m 39s
-
(Locked)
Refactor impure function to pure2m 21s
-
(Locked)
Reduce code side effects2m 18s
-
(Locked)
Refactor side effect example1m 4s
-
(Locked)
Don't mutate input arguments1m 8s
-
Use an immutable argument3m 41s
-
(Locked)
What about impure class properties3m 26s
-
(Locked)
-
-
-
-
-
-
-
-
-