SoFunction
Updated on 2025-04-11

Summary of commonly used custom functions in C#

This example summarizes several commonly used custom functions in C#, which are very practical. Share it for your reference. The details are as follows:

1. Convert array into string

/// <summary>
/// Convert array into string/// </summary>
/// <param name="glue">delimiter</param>/// <param name="pieces">Array of strings</param>private string Implode(char glue,string[] pieces) 
{
  string result = ;
  int count = ;
  for (int i = 0; i &lt; count;i++ )
  {
    if(i==0){
      result = pieces[i];
    }else{
      result = result + () + pieces[i];
    }        
  }      
  return result;    
}

Convert time format to Unix timestamp format

/// &lt;summary&gt;
/// Convert DateTime time format to Unix timestamp format/// &lt;/summary&gt;
/// &lt;param name=”time”&gt;&lt;/param&gt;
/// &lt;returns&gt;&lt;/returns&gt;
private int ConvertDateTimeInt( time)
{
   startTime = (new (1970, 1, 1));
  return (int)(time - startTime).TotalSeconds;
}

3. Generate random numbers in a certain range

/// &lt;summary&gt;
/// Get random numbers in a range/// &lt;/summary&gt;
/// <param name="start">The lower bound of random numbers</param>/// <param name="end">Upper boundary of random numbers</param>/// <returns> Random integers in the range [minValue, maxValue)</returns>private int GetRandomInt(int minValue, int maxValue)
{
  Random r = new Random(Chaos_GetRandomSeed());
  return (minValue, maxValue);
}

/// &lt;summary&gt;
/// Encrypt random number generator to generate random seeds/// &lt;/summary&gt;
/// &lt;returns&gt;&lt;/returns&gt;
private static int Chaos_GetRandomSeed()
{
  byte[] bytes = new byte[4];
   rng = new ();
  (bytes);
  return BitConverter.ToInt32(bytes, 0);
}

I hope this article will be helpful to everyone's C# programming