SoFunction
Updated on 2025-03-07

A summary of common mistakes made by newbies in C#

This article describes a common mistake for C# novices, but in fact, many experienced programmers often make these mistakes. I have specially compiled this for your reference. The details are as follows:

1. Error traversing List, for example, the following code:

List<String> strList =newList<String>
for(int i =0; i<; i++)
{
  (i);
}

This code looks like it deletes all elements. In fact, every call to the RemoveAt method will cause the List element index to be rearranged, and eventually the element is not completely deleted.
Can be changed to:

List<String> strList =newList<String>
for(int i =0; i<; i++)
{
  (i);
  i-=1;
}

This allows you to completely delete elements in List.

2. Errors about C# constants

For example, you wrote a class library and defined the following constants:

public const String str="First Version";

And this class library is referenced in another program. If you modify the constants in this class library and publish a new version, then run the previous program and you will find that the constants are still the original constants and have not changed. This is because when C# is compiled, constants are embedded directly as metadata. The solution is to recompile the entire solution or use properties instead of directly accessing the constants.

3. After packing the value type, if unboxing, it can only be disassembled into the original type before packing.,for example:

Int32 a=3;
Object obj=new object();
//The packing here will be successful and will not failobj=i;
//Unboxing will definitely failInt64 b=(Int64)obj;

You can do it like this:

Int64 b =(Int64)(Int32)obj;

You can complete the transformation

4. Error in overloading the == operator:

using System;
using ;
using ;
using ;
namespace UseOperator
{
  class Program
  {
    static void Main(string[] args)
    {
      Test t1 = new Test();
      ();
      ();
    }
  }
  class Test
  {
    public void MyFun()
    {
      Test t = new Test();
      if (t == null)
      {
        ("t is empty!");
      }
      else
      {
        ("t is not empty!");
      }
    }
    //The overloading algorithm with bugs exists    public static bool operator ==(Test t1, Test t2)
    {
      return (t1);
    }
    public static bool operator !=(Test t1, Test t2)
    {
      return !(t1 == t2);
    } 
    //Coverage HashCode    public override int GetHashCode()
    {
      return ();
    }
    public override bool Equals(object obj)
    {
      return (obj);
    }
  }
}

The problem here is that NULL will be passed into the == operator function in MyFun, resulting in an error during operation. The correct way is:

public static bool operator ==(Test t1, Test t2)
{
  if ((t2 as object) == null)
  {
    return (t1 as object) == null;
  }
  else
  {
    return (t1);
  }
}

5. The attributes or methods of calling structures in C# must use new to declare structure variables, otherwise an error will occur.

6. If params are used to use multiple parameters, it is necessary to determine whether the parameters are empty, otherwise the program will have hidden bugs.

7. Static members will be initialized when creating the first instance, and will only be initialized once. Do not use static members indiscriminately.

8. If you use the ref Object type parameter to accept String type, an error will occur. This is because C# requires that the parameters must use the correct type. It is okay not to add ref. If you must use the ref Object to accept String type parameters, you can first transform it into Object and then pass it with reference.

9. Never call virtual methods in the constructor of a class, such as:

using System;
using ;
using ;
using ;
namespace FransferVirtualFunction
{
  class Program
  {
    static void Main(string[] args)
    {
      try
      {
        Child ch = new Child();
      }
      catch (Exception ex)
      {
        ();
      }
      ();

    }
  }
  public class Ref
  {
    public string Str = "This is a member of the Ref class";
  }
  public class Parent
  {
    protected Ref my;
    public Parent()
    {
      my = new Ref();
      //The virtual method is called in the constructor      (GetString());
    }
    //Virtual method    public virtual string GetString()
    {
      return ;    //Used internal members    }
  }
  public class Child : Parent
  {
    private Ref my2;
    public Child()
      : base()
    {
      my2 = new Ref();
    }
    //Rewrite virtual method    public override string GetString()
    {
      return ;    //Used internal members    }
  }
}

Here, when executing the constructor of the base class, the virtual method GetString() of the derived class will be executed, and an exception will be thrown when obtaining, because the derived class object has not been constructed yet.

10. Pay attention to the meaning of NULL when communicating with C# and SQL Server. This value represents 1900-1-1 in SQL Server. The null value of SQL Server can be represented by DBNull.

That's all for the time being. Note that the above 10 points can reduce a large number of bugs during programming.

Replenish:

1. The parameters in the Math trigonometric function are radian values, not angle values.

2. Bugs caused by relative paths in WinForm: For details, please refer toWinForm relative path trap

3. When passing data using the serialized data format such as xml, json, etc., if the passed data is numerical type, it is best to convert it to string first and then tryParse to the corresponding type during parsing.

As for the reason: the third point above is the problem of packing and unboxing.

I believe that the description in this article can be of great help to everyone's C# programming.