How to do a null check

Checking for null is important in programming to avoid potential runtime errors, prevent crashes, and ensure the reliability and robustness of your code. In C#, we can check for null in few different ways, depending on the context. So far I have been using following methods: Using the equality operator 1 2 3 4 5 6 7 object obj = null; if (obj == null) { // if null, do something } Using the is keyword 1 2 3 4 5 6 7 object obj = null; if (obj is null) { // if null, do something } Using the ReferenceEquals() method 1 2 3 4 5 6 7 object obj = null; if (ReferenceEquals(obj, null)) { // if null, do something } Using the != opeartor 1 2 3 4 5 6 7 object obj = null; if (obj != null) { // object is not null } Using the null-conditional operator ?. 1 2 3 var text = null; int? length = text?.Length; // length will be null, if text is null Using the null-coalescing operator ?? 1 2 3 var text = null; var result = text ?? "default non-null value"; // if text is null, use the default value

March 11, 2024 · 1 min · 203 words

Access Modifiers

I have recently started learning C# language, which, compared to python, is a lot more verbose and structured. C# syntax is influenced by C and C++ languages. Part of CS50 Introduction to Computer Science course used C language, so having seen the syntax before helps a lot. However, working mostly with Python, there is a lot of difference. As I like to do, I will try to summarize key points as it helps me to learn and understand the language more. ...

February 25, 2024 · 3 min · 486 words