Demonstrating StringBuilder AppendFormat

image_pdfimage_print

   

    using System;
    using System.Text;

   class StringBuilderAppendFormat {
      static void Main(string[] args)
      {
         StringBuilder buffer = new StringBuilder();
         string string1, string2;

         string1 = "This {0} costs: {1:C}.
";

         object[] objectArray = new object[ 2 ];

         objectArray[ 0 ] = "Software";
         objectArray[ 1 ] = 1234.56;
         buffer.AppendFormat( string1, objectArray );

         string2 = "Number:{0:d3}.
" +
            "Number right aligned with spaces:{0, 4}.
" +
            "Number left aligned with spaces:{0, -4}.";

         buffer.AppendFormat( string2, 5 );
         Console.WriteLine(buffer.ToString());
      }
   } 

           
          


StringBuilder EnsureCapacity method

image_pdfimage_print

using System;
using System.Text;

class StringBuilderFeatures
{
static void Main(string[] args)
{
StringBuilder buffer =new StringBuilder( “Hello, how are you?” );

string output = “buffer = ” + buffer.ToString() +

Length = ” + buffer.Length +

Capacity = ” + buffer.Capacity;

buffer.EnsureCapacity( 75 );

output += ”

New capacity = ” +buffer.Capacity;

// truncate StringBuilder by setting Length property
buffer.Length = 10;

output += ”

New length = ” +
buffer.Length + ”
buffer = “;

// use StringBuilder indexer
for ( int i = 0; i < buffer.Length; i++ ) output += buffer[ i ]; Console.WriteLine( output); } } [/csharp]

Invalid Cast Exceptions with Implicit Operators

image_pdfimage_print
   
 


public class TestClass
{
    private MainClass MyMainClassObject;
   
    public TestClass()
    {
        MyMainClassObject = new MainClass();
    }
   
    public static implicit operator MainClass(TestClass Source)
    {
        return Source.MyMainClassObject;
    }
}
   
public class MainClass
{
    public static void Main()
    {
        object MyObject;
        MainClass MyMainClassObject;
   
        MyObject = new TestClass();
        MyMainClassObject = (MainClass)MyObject;
    }
}

    


stackalloc Demo

image_pdfimage_print

using System;

class MainEntryPoint {
static unsafe void Main() {
Console.Write(“How big an array do you want?
> “);
string userInput = Console.ReadLine();
uint size = uint.Parse(userInput);

long* pArray = stackalloc long[(int)size];
for (int i = 0; i < size; i++) pArray[i] = i * i; for (int i = 0; i < size; i++) Console.WriteLine("Element {0} = {1}", i, *(pArray + i)); } } [/csharp]