.NET 2.0: Notes on Foundation Part 2 (C#)

Explicit Conversion The following are methods for explicit conversion: System.Convert, (type) cast operator, type.ToString, type.Parse, type.TryParse, and type.TryParseExact.   Conversion in Custom Types The following are ways to provide conversion for your own types: conversion operators (which are new to .NET 2.0), ToString and Parse overrides, System.IConvertible implementation, and TypeConverter class implementation.   File System …

Continue reading .NET 2.0: Notes on Foundation Part 2 (C#)

Advertisements

.NET 2.0: Notes on Foundation Part 1

Nullable Type In .NET 2.0, you can declare a variable as Nullable: Nullable b = null; // or this which is a shorthand notation bool? b = null; String versus StringBuilder Strings are immutable in .NET. If you want to combine multiple strings, you can use String class’s Concat, Join, or Format methods or use StringBuilder class. Arrays To declare, initialize and sort an array: // Declare and initialize an array. int[] arr = { 3, 1, 2 }; // Call a shared/static array method. Array.Sort(arr); // Display the result. Console.WriteLine("{0}, {1}, {2}", arr[0], arr[1], arr[2]); Try/Catch/Finally Blocks Use multiple Catch blocks to filter exceptions, ordered from most specific to least specific. Make sure variables you want to access in the Finally block is declared outside of the Try block. You can also use nested Try/Catch/Finally blocks. Commonly Used Interfaces IComparable, IDisposable, IConvertible, ICloneable, IEquatable, and IFormattble are commonly used interfaces. Generics To declare a generic type: class Gen { public T t; public U u; public Gen(T _t, U _u) { t = _t; u = _u; } } To consume a generic type: // Add two strings using the Gen class Gen ga = new Gen("Hello, ", "World!"); Console.WriteLine(ga.t + ga.u); // Add a double and an int using the Gen class Gen gb = new Gen(10.125, 2005); Console.WriteLine(gb.t + gb.u); To use a constraint so that you are not limited to just the base Object class: class CompGen where T : IComparable { public T t1; public T t2; public CompGen(T _t1, T _t2) { t1 = _t1; t2 = _t2; } public T Max() { if (t2.CompareTo(t1) < 0) return t1; else return t2; } } Besides interface, you can also use a base class, a constructor or a reference or value type for your constraints.