{"id":75845,"date":"2022-10-19T08:52:22","date_gmt":"2022-10-19T06:52:22","guid":{"rendered":"https:\/\/drafts.code-maze.com\/?p=71781"},"modified":"2022-10-19T10:09:15","modified_gmt":"2022-10-19T08:09:15","slug":"csharp-programming-mistakes","status":"publish","type":"post","link":"https:\/\/code-maze.com\/csharp-programming-mistakes\/","title":{"rendered":"Common C# Programming Mistakes"},"content":{"rendered":"<p><span style=\"font-weight: 400;\">In this article, we are going to look at some common C# programming mistakes. We are pretty sure that there are a lot more mistakes that developers make while writing their projects, but here, we will try to summarize the ones we often noticed while working with other developers.<\/span><\/p>\n<div style=\"padding: 20px; border-left: 5px #dc2323 solid; display: block; margin-bottom: 20px; box-shadow: 1px 1px 5px 0px lightgrey;\">To download the source code for this article, you can visit our <a href=\"https:\/\/github.com\/CodeMazeBlog\/CodeMazeGuides\/tree\/main\/csharp-intermediate-topics\/CommonMistakesInACsharpProgram\" target=\"_blank\" rel=\"nofollow noopener\">GitHub repository<\/a>.<\/div>\n<p><span style=\"font-weight: 400;\">Let&#8217;s start with some beginner-level mistakes programmers make with the C# naming convention.<br \/>\n<\/span><\/p>\n<h2>Using The Wrong Naming Convention<\/h2>\n<p><span style=\"font-weight: 400;\">In programming, a convention refers to a set of guidelines that recommend the best practices to be followed for a particular language. Naming conventions are one of the most common mistakes known.\u00a0<\/span><\/p>\n<h3><strong>How To Properly Name a Class In C#<\/strong><\/h3>\n<p><span style=\"font-weight: 400;\">In C#, a class represents the blueprint of an object and should be named as nouns or noun phrases eg Car, Person, etc. <\/span><span style=\"font-weight: 400;\">C<\/span>lasses should be named with the pascal case convention. PascalCase is when every letter that starts a new word in your variable name is capitalized:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public class microwaveoven { } \/\/wrong\r\n\r\npublic class MicrowaveOven { } \/\/right\r\n<\/pre>\n<h3><strong>How To Properly Name an Interface In C#<\/strong><\/h3>\n<p><span style=\"font-weight: 400;\">We should name interfaces as nouns, noun phrases, or adjectives. When we declare an interface, we should prefix them with the letter I:<br \/>\n<\/span><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public interface Machine { } \/\/wrong\r\n\r\npublic interface IMachine { } \/\/right<\/pre>\n<h3><span style=\"font-weight: 400;\"><strong>How To Properly Name a Variable In C#<\/strong><\/span><\/h3>\n<p><span style=\"font-weight: 400;\">Variables should be named in such a way that they describe what they are holding. It is never okay to use abbreviations or single letters for variable names:<br \/>\n<\/span><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">int lv = 3; \/\/wrong\r\nint no_si = 20; \/\/wrong<\/pre>\n<p><span style=\"font-weight: 400;\">There are some exceptions to this rule. A typical example is when we declare a variable that holds an Id or URI:<\/span><\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">int id = 0; \/\/an exception to this rule<\/code><\/p>\n<p><span style=\"font-weight: 400;\">When declaring variable names we should not use underscores or hyphens as separators. They should also be named using the camel case notation:<br \/>\n<\/span><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">int levels = 3; \/\/right\r\nint numberOfStudents = 20; \/\/right\r\n<\/pre>\n<h3><strong>How To Properly Name a NameSpace In C#<\/strong><\/h3>\n<p><span style=\"font-weight: 400;\">A namespace is used to declare a scope that contains a set of related objects. Organizing our namespaces to show hierarchy makes our general structure well-defined:<\/span><\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">API.Services.Implementations.ProductService<\/code><\/p>\n<h3>How To Properly Name Constants In C#<\/h3>\n<p>Constants are immutable values known at compile time that remain the same throughout the duration of the program. They should be named using the Pascal case convention:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public const string FavoriteFood = \"Egusi Soup\"; \/\/right\r\n\r\npublic const string favoriteFood = \"Egusi Soup\"; \/\/wrong  \r\n      \r\npublic const string FAVORITEFOOD = \"Egusi Soup\"; \/\/wrong<\/pre>\n<h2>Misplacing Reference and Value Types<\/h2>\n<p>We categorize data types based on how their values are stored in memory. A data type is regarded as a value type if it holds a data value within its own memory space while a reference type contains a pointer to another memory location that holds the data:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public struct Person\r\n{\r\n    public string Name {get; set;}\r\n    public int Age {get; set;}\r\n}\r\n\r\npublic class Car\r\n{\r\n    public int Id {get; set;}\r\n    public string Name {get;\u00a0set;}\r\n}\r\n\r\npublic static void MisplaceTypes()\r\n{\r\n    Person personOne = new();\r\n    Person personTwo = new();\r\n\r\n    Console.WriteLine(personOne.Equals(personTwo)); \/\/True\r\n\r\n    Car carOne = new();\r\n    Car carTwo = new();\r\n\r\n    Console.WriteLine(carOne == carTwo); \/\/False\r\n}<\/pre>\n<p>When we compare new instantiation of struct types, the result shows that they are equal. This is not the same for classes because classes are reference types while structs are value types. From this, we start to see the issues that could arise if we make use of a reference type as if it were a value type or vice versa.<\/p>\n<h2><strong>Overlooking Extension Methods In C#<\/strong><\/h2>\n<p><span style=\"font-weight: 400;\">An <a href=\"https:\/\/code-maze.com\/csharp-static-members-constants-extension-methods\/#extensionmethods\" target=\"_blank\" rel=\"noopener\">extension method<\/a> will allow an existing type to be extended without relying on inheritance or having to change the source code. In other words, we can add custom methods to predefined types without having to recompile, create a new derived type or even modify the type being extended.<\/span><span style=\"font-weight: 400;\"><br \/>\n<\/span><span style=\"font-weight: 400;\"><br \/>\n<\/span><span style=\"font-weight: 400;\">Even though extension methods are very useful, they can get confusing. A lot of confusion arises when we go through or debug a codebase and find object-calling methods that are not defined on the types they\u2019re invoked on. <\/span><span style=\"font-weight: 400;\">Let&#8217;s demystify extension methods.<\/span><\/p>\n<p><span style=\"font-weight: 400;\">For starters, they are static methods that have the &#8220;this&#8221; keyword attached to their first parameter:<\/span><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public static class Extensions\r\n{\r\n    public static void PersonExtension(this Person person)\r\n    {\r\n        person.Name ??= \"A person\";\r\n        Console.WriteLine($\"{person.Name} is happy\");\r\n    }\r\n}<\/pre>\n<p><span style=\"font-weight: 400;\">After declaring an extension method, we can use it as though it is a native method of the extended object. To use it, we first need to call the namespace in which we declared:<\/span><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">using Extensions;\r\n\r\npublic class Application \r\n{ \r\n    public static void OverLookingExtensionTypes() \r\n    { \r\n        Person personOne = new(); \r\n        personOne.Name = \"John\"; \r\n        personOne.PersonExtension(); \/\/John is happy\r\n    }\r\n}<\/pre>\n<p><span style=\"font-weight: 400;\">As awesome as they sound, we should use them in moderation.<\/span><\/p>\n<p><strong>Extension methods cannot be used to override existing methods.<\/strong> If we try to declare an extension method with the same name and signature as an instance method of the type being extended; our extension method will not be called.\u00a0 Another important thing to note is that using an extension method is not a full-blown way to go about inheritance, this is because extension methods do not have access to private and protected members of the type they are extending.<\/p>\n<h2>Putting Too Much Load on Classes\u00a0<\/h2>\n<p><a href=\"https:\/\/code-maze.com\/csharp-intermediate-tutorial-oop\/\" target=\"_blank\" rel=\"noopener\"><em>Object-oriented<\/em>\u00a0programming<\/a> (<em>OOP<\/em>) is a programming structure where every program is organized around an object. As stated earlier, classes are blueprints for the creation of objects. When we design classes, we need to make sure they contain only the members that are relevant to them:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public class Drink\r\n{\r\n    public int Width { get; set; }\r\n    public int Height { get; set; } \r\n    public string Color { get; set; }\r\n    public string Taste { get; set; }\r\n\r\n    public void Break()\r\n    {\r\n        Console.WriteLine(\"Broken into pieces\");\r\n    }\r\n\r\n    public void Evaporating()\r\n    {\r\n        Console.WriteLine(\"Eveporating into thin air\");\r\n    }\r\n}<\/pre>\n<p>This is a badly written class because it has the properties of a bottle and a liquid. The proper thing to do is to consider these objects as separate entities. Some properties of the bottle are its width, height, and color, and some abilities of the bottle are its ability to break or its ability to get filled up with liquid.\u00a0\u00a0<\/p>\n<p>Some properties of the wine are its color, taste, and ability to evaporate. As we can see, the <code>Bottle<\/code> object does not need a lot of information that is concerned with the <code>Wine<\/code> object.<\/p>\n<p>The better approach here is the proper separation of concern:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public class Bottle\r\n{\r\n    public int Width { get; set; }\r\n    public int Height { get; set; }\r\n\r\n    public void Break()\r\n    {\r\n        Console.WriteLine(\"Broken into pieces\");\r\n    }\r\n}\r\n\r\npublic class Wine\r\n{\r\n    public string Color { get; set; }\r\n    public string Taste { get; set; }\r\n\r\n    public void Evaporate()\r\n    {\r\n        Console.WriteLine(\"Eveporating into thin air\");\r\n    }\r\n}\r\n\r\npublic class WineBottle\r\n{\r\n    public Wine Wine { get; set; }\r\n    public Bottle Bottle { get; set; }\r\n}<\/pre>\n<h2>Having a Jack-Of-All-Trade Method<\/h2>\n<p>Methods should have just one job. Having too many lines of code in a method is usually a red flag and most times it&#8217;s an indicator that our method has more than one responsibility:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public void JackOfAllTrade()\r\n{\r\n    try\r\n    {\r\n        Console.WriteLine(\"Whats your name?\");\r\n        string name = Console.ReadLine();\r\n\r\n        Console.WriteLine(\"How old are you?\");\r\n        int age = Convert.ToInt32(Console.ReadLine());\r\n\r\n        string welcomeMessage = $\"Welcome to the castle {name}\";\r\n        Console.WriteLine(welcomeMessage);\r\n        int count = 0;\r\n\r\n        foreach (var letter in name)\r\n        {\r\n            char[] vowels = { 'A', 'E', 'I', 'O', 'U' };\r\n            if (vowels.Contains(letter))\r\n                count++;\r\n        }\r\n\r\n        welcomeMessage = $\"Your name has {count} vowel(s)\";\r\n        Console.WriteLine(welcomeMessage);\r\n\r\n        Person person = new() { Name = name, Age = age };\r\n\r\n        if (count % 2 == 0)\r\n        {\r\n            person.Team = \"Team-even\";                    \r\n        }\r\n        else\r\n        {\r\n             person.Team = \"Team-Odd\";\r\n        }\r\n        people.Add(person);\r\n\r\n    }\r\n    catch (Exception ex)\r\n    {\r\n        Console.WriteLine(ex.Message);\r\n    }\r\n}<\/pre>\n<p>The <code>JackOfAllTrade<\/code> method combines a range of functionalities within one method body which makes it difficult to ascertain what it does.\u00a0 When we write methods like this, it makes our code difficult to read. A better approach will be to break up the code into sizable and reusable chunks:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public void HandleUser()\r\n{\r\n    (string name, int age) = CollectUserInfo();\r\n    RegisterUser(name, age);\r\n}\r\n\r\nprivate (string name, int age) CollectUserInfo()\r\n{\r\n    try\r\n    {\r\n        Console.WriteLine(\"Whats your name?\");\r\n        string name = Console.ReadLine();\r\n\r\n        Console.WriteLine(\"How old are you?\");\r\n        int age = Convert.ToInt32(Console.ReadLine());\r\n\r\n        string welcomeMessage = $\"Welcome to the castle {name}\";\r\n        Console.WriteLine(welcomeMessage);\r\n\r\n        return (name, age);\r\n    }\r\n    catch\r\n    {\r\n        Console.WriteLine(\"Age Should be a Number!\");\r\n    }\r\n            \r\n    return (default!, default);\r\n}\r\n \r\nprivate int GetVowelCount(string word)\r\n{\r\n    int count = 0;\r\n\r\n    foreach (var letter in word)\r\n    {\r\n        char[] vowels = { 'A', 'E', 'I', 'O', 'U' };\r\n        if (vowels.Contains(letter))\r\n        count++;\r\n    }\r\n    return count;\r\n}\r\n\r\nprivate void RegisterUser(string name, int age)\r\n{\r\n    int count = GetVowelCount(name);\r\n    Person person = new() { Name = name, Age = age };\r\n\r\n    if (count % 2 == 0)\r\n    {\r\n        person.Team = \"Team-even\";\r\n    }\r\n    else\r\n    {\r\n        person.Team = \"Team-Odd\";\r\n    }\r\n}<\/pre>\n<p>The beauty of this approach is that our methods can be reused in various parts of our codebase.<\/p>\n<h2>Using The &#8220;+&#8221; Operator For String Concatenation<\/h2>\n<p>The <code>string<\/code> is an immutable type. This means that any operation performed on a <code>string<\/code> creates a new instance in memory instead of modifying the previously defined one:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">string[] words = { \"doe\", \"is\", \"a\", \"developer\" };\r\nstring introduction = default;\r\n\r\nforeach (string word in words)\r\n{\r\n    introduction = introduction + word;\r\n}<\/pre>\n<p>Using this method will negatively impact the performance of our application.\u00a0\u00a0<\/p>\n<p>The <code>StringBuilder<\/code> class represents a string-like object whose value is a mutable sequence of characters:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">StringBuilder stringBuilder = new();\r\n\r\nforeach (string word in words)\r\n{\r\n   stringBuilder.Append(word).Append(\" \");\r\n}\r\n\r\nintroduction = stringBuilder.ToString(); <\/pre>\n<p>By utilizing <code>StringBuilder<\/code>, we can optimize our code by addressing the memory management issues of the <code>string<\/code> class.<\/p>\n<h2>Neglecting Exception Handling<\/h2>\n<p>An exception is a problem that appears unexpectedly from our codebase. Since we cannot avoid the occurrence of exceptions in the life cycle of an application, we should handle them.\u00a0 Exception handling is the process of building a system that can detect and manage exceptions. When they are not handled properly, exceptions will disrupt the application flow:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">Console.WriteLine(\"Whats your name?\");\r\nstring name = Console.ReadLine();\r\n\r\nConsole.WriteLine(\"How old are you?\");\r\nint age = Convert.ToInt32(Console.ReadLine());\r\n\r\nstring welcomeMessage = $\"Welcome! {name}\";\r\nConsole.WriteLine(welcomeMessage);\r\n\r\nreturn (name, age)<\/pre>\n<p>If we pass a string to the <code>age<\/code> variable that can&#8217;t be parsed, an exception will be thrown.<\/p>\n<p>A good approach is wrapping our code in try-catch blocks:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">try\r\n{\r\n    Console.WriteLine(\"Whats your name?\");\r\n    string name = Console.ReadLine();\r\n\r\n    Console.WriteLine(\"How old are you?\");\r\n    int age = Convert.ToInt32(Console.ReadLine());\r\n\r\n    string welcomeMessage = $\"Welcome to the castle {name}{age}\";\r\n    Console.WriteLine(welcomeMessage);  \r\n}\r\ncatch\r\n{\r\n    Console.WriteLine(\"Age Should be a Number!\");\r\n}\r\n            <\/pre>\n<p>This way, whenever exceptions pop up in our code the catch block will secure it. Check out our <a href=\"https:\/\/code-maze.com\/csharp-handling-exceptions\/\" target=\"_blank\" rel=\"noopener\">exception handling<\/a> and <a href=\"https:\/\/code-maze.com\/global-error-handling-aspnetcore\/\" target=\"_blank\" rel=\"noopener\">global exception handling<\/a> articles for more info.<\/p>\n<h2>Discarding The Stack Trace During Exception Handling<\/h2>\n<p>The stack trace is an execution stack that keeps track of all the methods in execution at a given instant:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public static void Run()\r\n{\r\n    Console.WriteLine(\"Start Program\");\r\n    Sum(6, 8);\r\n    Console.WriteLine($\"{Environment.StackTrace}\");\r\n\r\n   \/\/ Result: at System.Environment.get_StackTrace()\r\n   \/\/ at CommonMistakesInACsharpProgram.Application.DiscardStackTrace.Main() \r\n   \/\/ at Program.&lt;Main&gt;$(String[] args) \r\n}\r\n\r\npublic static int Sum(int numberOne, int numberTwo) =&gt; numberOne + numberTwo;\r\n<\/pre>\n<p>In case of an exception, the stack trace shows us the exact point where the exception happened. This is very helpful especially during debugging.<\/p>\n<p>When we encounter exceptions we are either tasked with handling the exceptions or <strong>delegating the exception handling to another component of our code<\/strong> using <code>throw ex<\/code>:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public static void TestMethod()\r\n{\r\n    try\r\n    {\r\n        Run();\r\n        ThrowError();\r\n        Sum(6, 8);\r\n    }\r\n    catch (Exception ex)\r\n    {\r\n        throw ex;\r\n    }\r\n}\r\n\r\npublic static void ThrowError() =&gt; throw new Exception(\"Custom Error\");<\/pre>\n<p>The problem with this delegating approach is we would lose the initial stack trace that gives us information about the origin of the exception.<\/p>\n<p>A better approach would be to use the <code>throw<\/code> keyword as this preserves the stack track from the origin of the exception up till the point where it is handled:\u00a0<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public static void TestMethod()\r\n{\r\n    try\r\n    {\r\n        Run();\r\n        ThrowError();\r\n        Sum(6, 8);\r\n    }\r\n    catch (Exception ex)\r\n    {\r\n        throw;\r\n    }\r\n}<\/pre>\n<h2>Overlooking The Possibility of Memory Leaks<\/h2>\n<p>The C# garbage collector manages memory automatically by disposing of objects that are no longer in use. This however does not guarantee the absence of memory leaks. A memory leak occurs when an object that is not in use is referenced in an application. In this scenario, the Garbage collector will not dispose of such an object because it looks useful.\u00a0<\/p>\n<p>Let&#8217;s look at some typical ways memory leaks can come up.<\/p>\n<p><strong>A memory leak may result from running a long thread that never releases objects.<\/strong> When we run these kinds of implementations within our code, we must be careful not to lock up objects that have no immediate use.<\/p>\n<p><strong>Another example arises from excessive caching.<\/strong> Caching enables us to store data in memory to improve accessibility. While this is an impressive feature, excessive use of caching can lead to an OutOfMemory exception. To manage this we can limit the size of the objects that we cache and also we should make sure that we are not adding unnecessary objects to the cache.<\/p>\n<p>Static objects are useful because we do not need to instantiate them. <strong>The only downside to this is that the Garbage collector does not dispose of static classes.<\/strong> We should endeavor to use static classes in moderation so we don&#8217;t shoot ourselves in the foot.<\/p>\n<p>We should also consider making use of the using statement which will automatically dispose of resources after execution.<\/p>\n<h2>Building Tightly Coupled Systems<\/h2>\n<p>A tightly coupled system is one in which all the components rely so much on each other, that removing or changing any one component will destroy the entire system.<\/p>\n<p>When we directly instantiate classes, we end up with a tightly coupled system. Instead, we should employ the use of dependency injection. With dependency injection, dependencies are injected into the client via a constructor, method, or property. To have a better grasp of this concept, check out our article on <a href=\"https:\/\/code-maze.com\/dependency-injection-aspnet\/\" target=\"_blank\" rel=\"noopener\">Dependency Injection<\/a>.<\/p>\n<h2>Using The Equality Operator For Null Checks in C#<\/h2>\n<p>The equality operator is a comparison operator that checks if its operands are equal:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">int value = 0;\r\nif (value == 1) Console.WriteLine(\"Hello World\");<\/pre>\n<p>A common mistake programmers make is using <code>==<\/code> for checking runtime types of objects. The problem with this approach of type check is that the equality operator is overloadable:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public class Complex\r\n{\r\n    private static int _id;\r\n    Random random = new();\r\n\r\n    public Complex() =&gt; _id = random.Next(200);\r\n            \r\n    public static bool operator ==(Complex c1, Complex c2) =&gt; _id % 2 == 0;    \r\n            \r\n    public static bool operator !=(Complex c1, Complex c2) =&gt; _id % 2 == 1;          \r\n\r\n    public int GetId =&gt; _id;            \r\n}<\/pre>\n<p>We have overloaded <code>==<\/code> to check if the <code>_id<\/code> property is even or odd.<\/p>\n<p>This becomes a problem, especially in cases when we use the equality operator for null check validations. The compiler will use the overloaded code version instead of the default one we want:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">Complex complexOne = new();\r\nConsole.WriteLine(complexOne.GetId); \/\/ A random valur from 0 - 200\r\n\r\nComplex complexTwo = new();\r\nConsole.WriteLine(complexTwo.GetId); \/\/ A random value from 0 -200\r\n\r\nif (complexOne == complexTwo)\r\n{\r\n    Console.WriteLine(\"Equal\");\r\n}<\/pre>\n<p>This code will have anomalies because <code>==<\/code> has been overloaded to behave differently.<\/p>\n<p>The <code>is<\/code> operator checks if the run-time type of an object is compatible with a given type. It is a better alternative in terms of null checks because it cannot be overridden and will always give us what we want:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">if (complexOne is complexTwo)\r\n{\r\n    Console.WriteLine(\"Equal\");\r\n}<\/pre>\n<h2>Returning Null Values For Empty Collections<\/h2>\n<p>It&#8217;s common for a method to return a collection in C#. A typical example is when we want to return all even numbers from a collection of numbers:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">List&lt;int&gt; numbers = new() { 1, 2, 3, 4, 5, 6, 7, 8, 9 };\r\n\r\nList&lt;int&gt;  evenNumbers = numbers.Where(x =&gt; x % 2 == 0).ToList();<\/pre>\n<p>The result is an actual collection because we have members in <code>numbers<\/code> that satisfy our condition.<\/p>\n<p>What if we had to return an empty collection, how do we return this? A common mistake is to return the empty collection as <code>null<\/code>:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public static IEnumerable&lt;Person&gt; GetUserByName(string name = null)\r\n{\r\n    if (string.IsNullOrWhiteSpace(name))\r\n    {\r\n        return null;\r\n    }\r\n\r\n    List&lt;Person&gt; users = new() \r\n    { \r\n        new Person { Age = 12, Name = \"John\" }, \r\n        new Person { Age = 34, Name = \"doe\" }, \r\n    };\r\n\r\n    return users.Where(x =&gt; x.Name == name);\r\n}<\/pre>\n<p>A better but inefficient method is to return a newly initialized collection. This is inefficient because every time we initialize an empty collection we consume memory space and assign unnecessary tasks to the garbage collector:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\"> public static IEnumerable&lt;Person&gt; GetUserByName(string name = null)\r\n{\r\n    if (string.IsNullOrWhiteSpace(name))\r\n    {\r\n        return new List&lt;Person&gt;();\r\n    }\r\n    \r\n    List&lt;Person&gt; users = new() \r\n    {\r\n        new Person { Age = 12, Name = \"John\" }, \r\n        new Person { Age = 3, Name = \"doe\" }, \r\n    };\r\n\r\n    return users.Where(x =&gt; x.Name == name);\r\n }<\/pre>\n<p>The best approach is to return the default empty collection:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public static IEnumerable&lt;Person&gt; GetUserByName(string name = null)\r\n{\r\n    if (string.IsNullOrWhiteSpace(name))\r\n    {\r\n        return Enumerable.Empty&lt;Person&gt;();\r\n    }\r\n    \r\n    List&lt;Person&gt; users = new() \r\n    { \r\n        new Person { Age = 12, Name = \"John\" }, \r\n        new Person { Age = 3, Name = \"doe\" }, \r\n    };\r\n\r\n    return users.Where(x =&gt; x.Name == name);\r\n}<\/pre>\n<h2>Conclusion<\/h2>\n<p>In this article, we have gone through some of the common C# programming mistakes and their prevention.\u00a0<\/p>\n<p>As we said, we are pretty sure that there are more of those. So, if you have some of those in mind, feel free to share them with us in the comment section.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this article, we are going to look at some common C# programming mistakes. We are pretty sure that there are a lot more mistakes that developers make while writing their projects, but here, we will try to summarize the ones we often noticed while working with other developers. Let&#8217;s start with some beginner-level mistakes [&hellip;]<\/p>\n","protected":false},"author":6,"featured_media":62189,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_et_pb_use_builder":"","_et_pb_old_content":"","_et_gb_content_width":"","footnotes":""},"categories":[12],"tags":[1461,1463,1462,1464],"class_list":["post-75845","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-csharp","tag-common-mistakes","tag-mistakes-in-c","tag-programming-mistakes","tag-programming-mistakes-in-c","et-has-post-format-content","et_post_format-et-post-format-standard"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v24.7 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Common C# Programming Mistakes - Code Maze<\/title>\n<meta name=\"description\" content=\"Let&#039;s look at some common C# programming mistakes. A common mistake is the use of wrong naming Conventions.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/code-maze.com\/csharp-programming-mistakes\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Common C# Programming Mistakes - Code Maze\" \/>\n<meta property=\"og:description\" content=\"Let&#039;s look at some common C# programming mistakes. A common mistake is the use of wrong naming Conventions.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/code-maze.com\/csharp-programming-mistakes\/\" \/>\n<meta property=\"og:site_name\" content=\"Code Maze\" \/>\n<meta property=\"article:published_time\" content=\"2022-10-19T06:52:22+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2022-10-19T08:09:15+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\" \/>\n\t<meta property=\"og:image:width\" content=\"1100\" \/>\n\t<meta property=\"og:image:height\" content=\"620\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"Code Maze\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@https:\/\/twitter.com\/CodeMazeBlog\" \/>\n<meta name=\"twitter:site\" content=\"@CodeMazeBlog\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Code Maze\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"13 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":[\"Article\",\"BlogPosting\"],\"@id\":\"https:\/\/code-maze.com\/csharp-programming-mistakes\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/code-maze.com\/csharp-programming-mistakes\/\"},\"author\":{\"name\":\"Code Maze\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/person\/09d29b223012c8e94a68ba62861d0b04\"},\"headline\":\"Common C# Programming Mistakes\",\"datePublished\":\"2022-10-19T06:52:22+00:00\",\"dateModified\":\"2022-10-19T08:09:15+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/code-maze.com\/csharp-programming-mistakes\/\"},\"wordCount\":1927,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\/\/code-maze.com\/#organization\"},\"image\":{\"@id\":\"https:\/\/code-maze.com\/csharp-programming-mistakes\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\",\"keywords\":[\"common mistakes\",\"mistakes in C#\",\"programming mistakes\",\"programming mistakes in C#\"],\"articleSection\":[\"C#\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/code-maze.com\/csharp-programming-mistakes\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/code-maze.com\/csharp-programming-mistakes\/\",\"url\":\"https:\/\/code-maze.com\/csharp-programming-mistakes\/\",\"name\":\"Common C# Programming Mistakes - Code Maze\",\"isPartOf\":{\"@id\":\"https:\/\/code-maze.com\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/code-maze.com\/csharp-programming-mistakes\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/code-maze.com\/csharp-programming-mistakes\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\",\"datePublished\":\"2022-10-19T06:52:22+00:00\",\"dateModified\":\"2022-10-19T08:09:15+00:00\",\"description\":\"Let's look at some common C# programming mistakes. A common mistake is the use of wrong naming Conventions.\",\"breadcrumb\":{\"@id\":\"https:\/\/code-maze.com\/csharp-programming-mistakes\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/code-maze.com\/csharp-programming-mistakes\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/code-maze.com\/csharp-programming-mistakes\/#primaryimage\",\"url\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\",\"contentUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\",\"width\":1100,\"height\":620,\"caption\":\"C# Development\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/code-maze.com\/csharp-programming-mistakes\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/code-maze.com\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Common C# Programming Mistakes\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/code-maze.com\/#website\",\"url\":\"https:\/\/code-maze.com\/\",\"name\":\"Code Maze\",\"description\":\"Learn. Code. Succeed.\",\"publisher\":{\"@id\":\"https:\/\/code-maze.com\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/code-maze.com\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/code-maze.com\/#organization\",\"name\":\"Code Maze\",\"url\":\"https:\/\/code-maze.com\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png\",\"contentUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png\",\"width\":3511,\"height\":3510,\"caption\":\"Code Maze\"},\"image\":{\"@id\":\"https:\/\/code-maze.com\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/x.com\/CodeMazeBlog\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/person\/09d29b223012c8e94a68ba62861d0b04\",\"name\":\"Code Maze\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez-150x150.png\",\"contentUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez-150x150.png\",\"caption\":\"Code Maze\"},\"description\":\"This is the standard author on the site. Most articles are published by individual authors, with their profiles, but when several authors have contributed, we publish collectively as a part of this profile.\",\"sameAs\":[\"https:\/\/www.linkedin.com\/company\/codemaze\/\",\"https:\/\/x.com\/https:\/\/twitter.com\/CodeMazeBlog\"],\"url\":\"https:\/\/code-maze.com\/author\/codemazecontributor\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Common C# Programming Mistakes - Code Maze","description":"Let's look at some common C# programming mistakes. A common mistake is the use of wrong naming Conventions.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/code-maze.com\/csharp-programming-mistakes\/","og_locale":"en_US","og_type":"article","og_title":"Common C# Programming Mistakes - Code Maze","og_description":"Let's look at some common C# programming mistakes. A common mistake is the use of wrong naming Conventions.","og_url":"https:\/\/code-maze.com\/csharp-programming-mistakes\/","og_site_name":"Code Maze","article_published_time":"2022-10-19T06:52:22+00:00","article_modified_time":"2022-10-19T08:09:15+00:00","og_image":[{"width":1100,"height":620,"url":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","type":"image\/png"}],"author":"Code Maze","twitter_card":"summary_large_image","twitter_creator":"@https:\/\/twitter.com\/CodeMazeBlog","twitter_site":"@CodeMazeBlog","twitter_misc":{"Written by":"Code Maze","Est. reading time":"13 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":["Article","BlogPosting"],"@id":"https:\/\/code-maze.com\/csharp-programming-mistakes\/#article","isPartOf":{"@id":"https:\/\/code-maze.com\/csharp-programming-mistakes\/"},"author":{"name":"Code Maze","@id":"https:\/\/code-maze.com\/#\/schema\/person\/09d29b223012c8e94a68ba62861d0b04"},"headline":"Common C# Programming Mistakes","datePublished":"2022-10-19T06:52:22+00:00","dateModified":"2022-10-19T08:09:15+00:00","mainEntityOfPage":{"@id":"https:\/\/code-maze.com\/csharp-programming-mistakes\/"},"wordCount":1927,"commentCount":0,"publisher":{"@id":"https:\/\/code-maze.com\/#organization"},"image":{"@id":"https:\/\/code-maze.com\/csharp-programming-mistakes\/#primaryimage"},"thumbnailUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","keywords":["common mistakes","mistakes in C#","programming mistakes","programming mistakes in C#"],"articleSection":["C#"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/code-maze.com\/csharp-programming-mistakes\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/code-maze.com\/csharp-programming-mistakes\/","url":"https:\/\/code-maze.com\/csharp-programming-mistakes\/","name":"Common C# Programming Mistakes - Code Maze","isPartOf":{"@id":"https:\/\/code-maze.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/code-maze.com\/csharp-programming-mistakes\/#primaryimage"},"image":{"@id":"https:\/\/code-maze.com\/csharp-programming-mistakes\/#primaryimage"},"thumbnailUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","datePublished":"2022-10-19T06:52:22+00:00","dateModified":"2022-10-19T08:09:15+00:00","description":"Let's look at some common C# programming mistakes. A common mistake is the use of wrong naming Conventions.","breadcrumb":{"@id":"https:\/\/code-maze.com\/csharp-programming-mistakes\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/code-maze.com\/csharp-programming-mistakes\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/code-maze.com\/csharp-programming-mistakes\/#primaryimage","url":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","contentUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","width":1100,"height":620,"caption":"C# Development"},{"@type":"BreadcrumbList","@id":"https:\/\/code-maze.com\/csharp-programming-mistakes\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/code-maze.com\/"},{"@type":"ListItem","position":2,"name":"Common C# Programming Mistakes"}]},{"@type":"WebSite","@id":"https:\/\/code-maze.com\/#website","url":"https:\/\/code-maze.com\/","name":"Code Maze","description":"Learn. Code. Succeed.","publisher":{"@id":"https:\/\/code-maze.com\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/code-maze.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/code-maze.com\/#organization","name":"Code Maze","url":"https:\/\/code-maze.com\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/code-maze.com\/#\/schema\/logo\/image\/","url":"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png","contentUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png","width":3511,"height":3510,"caption":"Code Maze"},"image":{"@id":"https:\/\/code-maze.com\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/x.com\/CodeMazeBlog"]},{"@type":"Person","@id":"https:\/\/code-maze.com\/#\/schema\/person\/09d29b223012c8e94a68ba62861d0b04","name":"Code Maze","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/code-maze.com\/#\/schema\/person\/image\/","url":"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez-150x150.png","contentUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez-150x150.png","caption":"Code Maze"},"description":"This is the standard author on the site. Most articles are published by individual authors, with their profiles, but when several authors have contributed, we publish collectively as a part of this profile.","sameAs":["https:\/\/www.linkedin.com\/company\/codemaze\/","https:\/\/x.com\/https:\/\/twitter.com\/CodeMazeBlog"],"url":"https:\/\/code-maze.com\/author\/codemazecontributor\/"}]}},"_links":{"self":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts\/75845","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/users\/6"}],"replies":[{"embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/comments?post=75845"}],"version-history":[{"count":5,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts\/75845\/revisions"}],"predecessor-version":[{"id":75925,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts\/75845\/revisions\/75925"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/media\/62189"}],"wp:attachment":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/media?parent=75845"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/categories?post=75845"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/tags?post=75845"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}