Advantages of Generics in C#
Generics are very useful in C# for storing data and they have the following advantages:
1. Generics allow code reuse for different data types.
2. Generics provide type safety.
3. Generics reduce the number of casting and boxing needed to store value types.
Implementing Stack<T> in C# class
The example below shows how we can implement a generic stack class in c# that can hold upto 100 objects.
public class Stack <T> { int itemposition; T[] data = new T[100]; public void push(T obj) { data [itemposition++] = obj; } public T Pop() { return data [--itemposition]; } }
stack<T> collection in c#
An example of stack<T> use in c#:
Stack<int> stack = new Stack <int>(); stack.Push(1); stack.Push(2); int x = stack.Pop() / / x is 2 int y = stack.Pop() / / y is 1
yield break in C#
The yield break instruction specifies that the iterator block is to be abandoned prematurely, without having to add more elements. Below is an example of yield break in c#. A return statement in an iterator block is not allowed therefore you must instead use yield break.
static IEnumerable <string> Foo (bool breakit) { yield return "This One"; yield return "That One"; if (breakit) yield break; yield return "Another One"; }
Using multiple yield statements in an iterator
static void Main () { foreach (string s in getty()) Console.Write (s + " ") // There you go } static IEnumerable<string> getty() { yield return "There"; yield return "you"; yield return "go"; }
Use an iterator to return a sequence of Fibonacci numbers in C#
using System; using System; class FibTest { static void Main () { foreach (int fib in Fibs (6)) Console.Write (fib + ""); } static IEnumerable <int> Fibs (int fibCount) { for (int i = 0, prevFib = 1, curFib = 1; i <fibCount; i++) { yield return prevFib; int = newFib prevFib curFib +; prevFib = curFib; curFib = newFib; } } }
Output: 1 1 2 3 5 8
Using GetEnumerator to access characters in C# string
Below is an example of using GetEnumerator method of a collection to access characters in a string and display them.
var enumerator = "This is my string".GetEnumerator(); while (enumerator.MoveNext()) { var element = enumerator.Current ; Console.WriteLine (element); }
What is c# enumerator and enumerable?
An enumerator is a cursor that is read only and moves forward only through a sequence of values.
An enumerator is an object that:
1. Implements IEnumerator
2. Has a method called MoveNext for iterating over the sequence, and a property called Current provides for the reading of the current element of the sequence.
The foreach statement iterates over a enumerable Object. The enumerable object is the logical representation of a sequence and is not itself a cursor.
An enumerable object is an object that:
1. Implements either IEnumerable
2. Has a method called GetEnumerator that returns an enumerator.
Structure of an enumerator in c#
class enumerator // Implements IEnumerator { public IteratorVariableType Current {get {...}} public bool MoveNext () {...} } class Enumerable // implements IEnumerable { public Enumerator GetEnumerator () {...} }
C# Enqueue and Dequeue queue operations
Queue<string> myQueue = new Queue<string>(); void AddQueueItem(string request) { myQueue.Enqueue(request) ; } string GetNextQueueItem() { return myQueue.Dequeue() ; }
Stack push and pop in C#
Stack<string> myStack = new Stack<string>() ; void addRecord(string move) { myStack.Push(move); } string GetLastRecord() { return myStack.Pop(); }
Arraylist properties and methods in C#
ArrayList alphaList = new ArrayList(); alphaList.Add("A"); alphaList.Add("D"); alphaList.Add("W"); Console.WriteLine("Original Capacity"); Console.WriteLine(alphaList.Capacity); Console.WriteLine("Original Values"); foreach (object alpha in alphaList) { Console.WriteLine(alpha); } alphaList.Insert(alphaList.IndexOf("D") , "C"); alphaList.Insert(alphaList.IndexOf("W") , "J"); Console.WriteLine("New Capacity"); Console.WriteLine(alphaList. Capacity); Console.WriteLine("New Values"); foreach (object alpha in alphaList) { Console.WriteLine(alpha); }
Declare and fill a two-dimensional array in C#
int[, ] my2DArray = { { 1, 1 }, { 3, 5 }, { 5, 7 } }; for (int i = 0; i <= my2DArray. GetUpperBound(0) ; i++) { for (int x = 0; x <= my2DArray.GetUpperBound(1); x++) { Console.WriteLine("Index = [{0},{1}] Value = {2}", i, x, my2DArray[i, x] ); } }
Foreach loop to iterate through the elements of the array in C#
int[] intArray = { 1, 2, 3, 4, 5 }; Console.WriteLine("Upper Bound"); Console.WriteLine(intArray. GetUpperBound(0) ); Console.WriteLine("Array elements") ; foreach (int item in intArray) { Console.WriteLine(item) ; } Array.Reverse(intArray) ; Console.WriteLine("Array reversed") ; foreach (int item in intArray) { Console.WriteLine(item) ; } Array.Clear(intArray, 2, 2) ; Console.WriteLine("Elements 2 and 3 cleared") ; foreach (int item in intArray) { Console.WriteLine(item) ; } intArray[ 4] = 9; Console.WriteLine("Element 4 reset"); foreach (int item in intArray) { Console.WriteLine(item) ; } Console.ReadLine();
Convert Enum to Array dynamically in C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ProgramEmumtoArray { class ProgramEmumtoArray { static void Main(string[] args) { string[] people = Enum.GetNames(typeof(People)); foreach (var person in people) { Console.WriteLine(person); } Console.Read(); } enum People { Gandhi, Anthony, Obama, Mani } } }
Output:
Dynamic enumeration of Enum in C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace w3mentorConsoleApp { class Program { static void Main(string[] args) { foreach (var car in Enum.GetValues(typeof(Cars))) { Console.WriteLine(Enum.GetName(typeof(Cars), car)); } Console.Read(); } enum Cars { Ferrari, Polo, GMC, FordExplorer } } }
Sorting a hashtable in C#
Hashtable myHashTable = new Hashtable(); myHashTable.Add("1", "dotnet"); myHashTable.Add("2", "tutorials"); myHashTable.Add("3", "w3mentor"); List<int> myList = new List<int>(); foreach (var key in hash.Keys) { myList.Add(int.Parse(key.ToString())); } //sort the hashtable myList.Sort(); foreach (var item in myList) { Console.WriteLine(string.Format("{0},{1}", item, hash[item.ToString()])); } Console.Read();
Pass parameters for array initialization using command-line arguments in C#
using System; public class commandlineInitArray { public static void Main( string[] args ) { // check number of command-line arguments if ( args.Length != 3 ) Console.WriteLine( "Error: Please re-enter the entire command, including\n" + "an array size, initial value and increment." ); else { // get array size from first command-line argument int arrayLength = Convert.ToInt32( args[ 0 ] ); int[] array = new int[ arrayLength ]; // create array // get initial value and increment from command-line argument int initialValue = Convert.ToInt32( args[ 1 ] ); int increment = Convert.ToInt32( args[ 2 ] ); // calculate value for each array element for ( int counter = 0; counter < array.Length; counter++ ) array[ counter ] = initialValue + increment * counter; Console.WriteLine( "{0}{1,8}", "Index", "Value" ); // display array index and value for ( int counter = 0; counter < array.Length; counter++ ) Console.WriteLine( "{0,5}{1,8}", counter, array[ counter ] ); } // end else } // end Main } // end class commandlineInitArray
Pass multiple parameters in a single array in C#
using System; public class MultipleParamArray { // calculate average public static double Average( params double[] numbers ) { double total = 0.0; // initialize total // calculate total using the foreach statement foreach ( double d in numbers ) total += d; return total / numbers.Length; } // end method Average public static void Main( string[] args ) { double d1 = 10.0; double d2 = 20.0; double d3 = 30.0; double d4 = 40.0; Console.WriteLine( "d1 = {0:F1}\nd2 = {1:F1}\nd3 = {2:F1}\nd4 = {3:F1}\n", d1, d2, d3, d4 ); Console.WriteLine( "Average of d1 and d2 is {0:F1}", Average( d1, d2 ) ); Console.WriteLine( "Average of d1, d2 and d3 is {0:F1}", Average( d1, d2, d3 ) ); Console.WriteLine( "Average of d1, d2, d3 and d4 is {0:F1}", Average( d1, d2, d3, d4 ) ); } // end Main } // end class MultipleParamArray
Rectangular and jagged arrays in C#
using System; public class RectangleJaggedArray { // create and output rectangular and jagged arrays public static void Main( string[] args ) { // with rectangular arrays, // every column must be the same length. int[ , ] rectangular = { { 1, 2, 3 }, { 4, 5, 6 } }; // with jagged arrays, // we need to use "new int[]" for every row, // but every column does not need to be the same length. int[][] jagged = { new int[] { 1, 2 }, new int[] { 3 }, new int[] { 4, 5, 6 } }; OutputArray( rectangular ); // displays array rectangular by row Console.WriteLine(); // output a blank line OutputArray( jagged ); // displays array jagged by row } // end Main // output rows and columns of a rectangular array public static void OutputArray( int[ , ] array ) { Console.WriteLine( "Values in the rectangular array by row are" ); // loop through array's rows for ( int row = 0; row < array.GetLength( 0 ); row++ ) { // loop through columns of current row for ( int column = 0; column < array.GetLength( 1 ); column++ ) Console.Write( "{0} ", array[ row, column ] ); Console.WriteLine(); // start new line of output } // end outer for } // end method OutputArray // output rows and columns of a jagged array public static void OutputArray( int[][] array ) { Console.WriteLine( "Values in the jagged array by row are" ); // loop through each row foreach ( var row in array ) { // loop through each element in current row foreach ( var element in row ) Console.Write( "{0} ", element ); Console.WriteLine(); // start new line of output } // end outer foreach } // end method OutputArray } // end class RectangleJagged


