Generate random values in C#

all sorts of random values including date, times, numbers, binary, bit, etc.

Nothing new here, but it's nice to have it all in one spot.

generate random values

public int Integer(int max = Int16.MaxValue)
{
    max = max > Int16.MaxValue ? Int16.MaxValue : max;
    return new Random().Next(-max, max);
}

public string Binary(int length = 8)
{            
    int decNum = new Random().Next(1000, int.MaxValue);
    return Convert.ToString(decNum, 2)
        .Substring(0, length);
}

public DateTime Date(int start_year = 1995)
{
    DateTime start = new DateTime(start_year, 1, 1);
    int range = ((TimeSpan)(DateTime.Today - start))
        .Days;
    start.AddDays(new Random().Next(range))
        .AddSeconds(new Random().Next(86400));
}

public TimeSpan Time()
{
    return Date().TimeOfDay;
}

public int Bit()
{
    return new Random().Next() % 2 == 0 ? 1 : 0;
}

public bool Bool()
{
    return new Random().Next() % 2 == 0 ? true : false;
}

public string String(int limit = 255)
{
    // added spaces so there will be 
    // a higher chance of spacing words
    string legal = "        abcdefghijklmnopqrstuvwxyz" +
        "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789      ";
    StringBuilder s = new StringBuilder();
    //Random length for the string
    limit = new Random().Next(1, limit); 
    for (int i = 0; i < limit; i++)
        s.Append(legal[new Random().Next(legal.Length)]);
    return s.ToString();
}

Pingbacks and trackbacks (4)+

Add comment

Loading