A random color extension method for VB.Net and C# (System.Drawing)


This is just a simple extension method off of System.Drawing.Color that will return a random color.

VB.Net

Imports System.Runtime.CompilerServices

Public Module ColorExtensions

    ''' <summary>
    ''' Creates a random color and returns it.
    ''' </summary>
    ''' <param name="c"></param>
    <Extension()> _
    Public Function RandomColor(ByVal c As System.Drawing.Color) As System.Drawing.Color
        Dim rand As New Random
        Return Color.FromArgb(rand.Next(0, 256), rand.Next(0, 256), rand.Next(0, 256))
    End Function

End Module

C#

using System.Runtime.CompilerServices;

public static class ColorExtensions
{
    /// <summary>
    /// Creates a random color and returns it.
    /// </summary>
    /// <param name="c"></param>
    public static System.Drawing.Color RandomColor(this System.Drawing.Color c)
    {
        Random rand = new Random();
        return Color.FromArgb(rand.Next(0, 256), rand.Next(0, 256), rand.Next(0, 256));
    }
}

Leave a comment

Please note that we won't show your email to others, or use it for sending unwanted emails. We will only use it to render your Gravatar image and to validate you as a real person.