From the course: Advanced C#: Functional Programming Patterns
Unlock this course with a free trial
Join today to access over 24,800 courses taught by industry experts.
Simple immutable example - C# Tutorial
From the course: Advanced C#: Functional Programming Patterns
Simple immutable example
For this example, I'll use the DateTime structure in .NET, which is an immutable type. So here I'm declaring two variables of DateTime. And then because I have constructors that allow me to initialize the properties, I would call this constructor. Now the DateTime has multiple constructors. I'm calling one of those constructors that takes three arguments: the year, the month, and the day. So at this point, after line 18, the state of the DateTime structure is fixed. I can't modify it. Now I can get the information from the DateTime instance like this. There's a day property. I can read that value. But if I were to try to change that value, uncomment this line, I'll get a compile error and the error is property or indexer, DateTime.Day cannot be assigned to, it is read-only. So what if I wanted to add three days to the current date? What that would look like is since the only way we can set the properties is via the constructor, I'd have to instantiate a new type, then take the…
Contents
-
-
-
-
-
-
-
Principles of immutable types2m 10s
-
(Locked)
Simple immutable example1m 51s
-
(Locked)
More principles2m 49s
-
(Locked)
Read-only properties2m 44s
-
(Locked)
Instance method in immutable type3m 10s
-
(Locked)
Use helper methods to create new instance2m 23s
-
(Locked)
Use factory method to create instance3m 30s
-
-
-
-
-
-
-