/
TheHitchhikersGuideToTheGalaxy.cs
44 lines (41 loc) · 1.14 KB
/
TheHitchhikersGuideToTheGalaxy.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
namespace Sturla.io.Misc
{
public class TheHitchhikersGuideToTheGalaxy
{
public void WithoutPatternMatching()
{
var useDeepThought = false;
var answer = CalculateTheAnswerToTheUltimateQuestion(useDeepThought);
// Verbose null checking. Of course we could do if(answer != null)
// but I think that is not as to the point as the second method below.
if (answer == null)
{
System.Console.WriteLine($"Sorry the answer could´t be calculated. Return value was null");
}
else
{
System.Console.WriteLine($"The answer is {answer}");
}
}
public void WithPatternPatternMatching()
{
var useDeepThought = false;
if (CalculateTheAnswerToTheUltimateQuestion(useDeepThought) is int answer)
{
//If result from method is int (not null) we go in here with some value in answer
System.Console.WriteLine($"The answer is {answer}");
}
else
{
System.Console.WriteLine($"Sorry the answer could´t be calculated. Return value was null");
}
}
private int? CalculateTheAnswerToTheUltimateQuestion(bool useDeepThought)
{
if (useDeepThought)
return 42;
else
return null;
}
}
}