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

Posted by Blake on 7/29/2012
)

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>
    ''' <returns></returns>
    ''' <remarks></remarks>
    <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>
    /// <returns></returns>
    /// <remarks></remarks>
    [Extension()]
    public static System.Drawing.Color RandomColor(System.Drawing.Color c)
    {
        Random rand = new Random();
        return Color.FromArgb(rand.Next(0, 256), rand.Next(0, 256), rand.Next(0, 256));
    }

}