C# Extension Method: Array - SetByte

CSharp · Console

/Program.cs

// C# Extension Method
// Doc: https://csharp-extension.com/en/method/1002180/array-setbyte

// @nuget: Z.ExtensionMethods

using System;

public class Program
{
	public static void Main( )
    {
        short[ ] shorts = new short[ 10 ];
        long[ ]  longs  = new long[ 3 ];

        Console.WriteLine( "This example of the Array.SetByte(int, byte) method generates the following output.\n");
        Console.WriteLine( "  Initial values of arrays:\n" );

        DisplayArray( shorts, "shorts" );
        DisplayArray( longs, "longs" );

        Console.WriteLine( "\nArray values after setting:\n\n  byte 3 = 25\n  byte 6 = 64\n  byte 12 = 121\n  byte 17 = 196:\n" );

		// C# Extension Method: Array - SetByte
        shorts.SetByte(3, 25);
        shorts.SetByte( 6, 64);
        shorts.SetByte(12, 121);
        shorts.SetByte(17, 196);
        longs.SetByte(3, 25);
        longs.SetByte(6, 64);
        longs.SetByte(12, 121);
        longs.SetByte(17, 196);

        // Display the arrays again.
        DisplayArray( shorts, "shorts" );
        DisplayArray( longs, "longs" );
    }
	
	// Display the array contents in hexadecimal.
    public static void DisplayArray(Array arr, string name)
    {
        int elemWidth = arr.ByteLength() / arr.Length;
        string format = String.Format( " {{0:X{0}}}", 2 * elemWidth );

        Console.Write( "{0,7}:", name );
		
        for( int loopX = arr.Length - 1; loopX >= 0; loopX-- )
		{
            Console.Write(format, arr.GetValue(loopX) );
		}
		
        Console.WriteLine( );
    }
}
;