Finalizers in C#
Finalizers are class methods that are executed before the garbage collector frees the memory of a referenced object no longer in use. The syntax for a finalizer is the name of the class to which the tilde sign ~ preceeds:
class TestClass1 { ~ TestClass1 () {... } }
The above code is converted by the compiler to the following method declaration:
protected override void Finalize () { ... base.Finalize (); }
Embedded types in C#
An embedded type in C# is declared within the scope of another type.
public class FirstLevel { public class NestedClass {} // embedded Class public enum Color {Red, Blue, Tan} // Embedded Enum }
An embedded type has the following features:
1. The embedded type can access the private members of enclosing type and all other types that the enclosing type has access to.
2. The embedded type can have all possible access modifiers and is not limited to public and internal.
3. The default visibility for an embedded type is private and not internal.
4. Access to an embedded type from outside the enclosing type requires a qualification by the name of the enclosing type (such as when accessing static members).
For example, to access Color.Red from outside our FirstLevel class, we would write the following:
FirstLevel.Color color = FirstLevel.Color.Red;
All types can be embedded within classes and structs. Embedded types are intensively used by the compiler itself, it generates private classes that manage the state in constructs such as iterators and anonymous methods.
Nullable types in c#
Reference types in c# can have non-existing value with a zero reference. However, For value types this is usually not possible:
string s = null; // OK, reference-type int i = 0; // compile-time, value-type can not be null
To represent zero in a value type, you need a special construct called Nullable Type . To use a nullable type, the value type is followed by a question mark ?.
Example of nullable type integer:
int?i = 0; // ok since it is nullable type Console.WriteLine(i == 0) // true
Advantages of call stack during debugging
The call stack can be useful in a number of situations during debugging:
1. The call stack lets us determine when a method is called too early i.e when we invoke the method before the data it requires to function is ready.
2. The call stack helps to determine when a method is called too late i.e after the event is over.
3. The call stack can also help you locate the source of an exception when the exception has been passed up from an underlying class.
4. The call stack also helps to see how the method is called when the method could be called from multiple locations.
Display the call stack method names in C#
using System.Diagnostics; [STAThread] public static void Main() { //obtain call stack StackTrace stackTrace = new StackTrace(); // obtain method calls (frames) StackFrame[] stackFrames = stackTrace.GetFrames(); // display method names foreach (StackFrame stackFrame in stackFrames) { Console.WriteLine(stackFrame.GetMethod().Name); // output method name } }
Get Name of the calling method using Reflection in C#
using System.Diagnostics; // get call stack StackTrace stackTrace = new StackTrace(); // get calling method name Console.WriteLine(stackTrace.GetFrame(1).GetMethod().Name);
Strip out all html tags in string using C#
The tags need not be correctly nested for the below implementation to work..
public static string RemoveHtmlTags(string pInput) { char[] array = new char[pInput.Length]; int arrayIndex = 0; bool inside = false; for (int i = 0; i < pInput.Length; i++) { char let = pInput[i]; if (let == '<') { inside = true; continue; } if (let == '>') { inside = false; continue; } if (!inside) { array[arrayIndex] = let; arrayIndex++; } } return new string(array, 0, arrayIndex); }
Cloning C# objects using MemberwiseClone
public CarClass GetCopy() { return MemberwiseClone() as CarClass; } CarClass beta = new CarClass(); CarClass newcar = beta.GetCopy(); bool areCarsEqual = ReferenceEquals(beta, newcar); Console.WriteLine("Are cars Equal?: {0}",areCarsEqual);
Example of stringbuilder append operation in C#
void demoAppendSB() { StringBuilder sb; sb = new StringBuilder("This is the existing text"); sb.Append("This will be appended"); Console.WriteLine("sb.Append(\"Appended\"): {0}",sb); }
Using TrimStart and TrimEnd in C# strings
The TrimStart function in C# removes all occurances of a string/character from the beginning of an input string.
string testInput="001"; Int val=Conver.ToInt32(testInput.TrimStart('0')); Console.WriteLine(val);
Ouput: 1
We can use the TrimEnd function if we need to remove the character at the end of the string. The TrimEnd function in C# removes all occurances of a string/character from the end of an input string.
string testInput="001000000"; Int val=Conver.ToInt32(testInput.TrimEnd('0')); Console.WriteLine(val);
Output: 001
Find minimum and maximum supported decimal values in C#
We can use the following code to find the range for a decimal datatype
Console.WriteLine("Minimum value=" + decimal.MinValue); Console.WriteLine("Maximum value=" + decimal.MaxValue); Console.ReadKey();
Example using Call By Out parameter in C#
public class OPExample { public void Addme(int x, int y, out int result) { result = x + y; } static void Main(string[] args) { OPExample obj = new OPExample(); int a = 1, b = 2, result; obj.Addme(a, b, out result); Console.WriteLine("Out Parameter Result is =" + result); Console.ReadKey(); } }
Getting all installed printers in system using C# .NET
If a printer is installed on the machine, the following code will list the installed printer(s) in the system. Add a listbox named printersList to a windows form and use the following in the form_load.
using System.Drawing.Printing; private void Form1_Load(object sender, EventArgs e) { foreach (String printer in PrinterSettings.InstalledPrinters) { printersList.Items.Add(printer.ToString()); } }
Linq style query to change string case in C#
static string toggleStringCase(string input) { return (from c in input select new string(Char.IsLower(c) ? Char.ToUpper(c) : Char.ToLower(c), 1)).Aggregate((a, b) => a += b); }
Using StringBuilder to change string case in C#
string s = "thISisAtestSTringForCaseConversion"; var sb = new StringBuilder(s.Length); foreach (char c in s) sb.Append(char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c)); s = sb.ToString();
Function to change string case in C#
public string ToggleCharacterCase(string PInput) { string strResult = string.Empty; char[] arrInput = PInput.ToCharArray(); foreach (char objChar in arrInput) { if (char.IsLower(objChar)) strResult += objChar.ToString().ToUpper(); else if (char.IsUpper(objChar)) strResult += objChar.ToString().ToLower(); else strResult += objChar.ToString(); } return strResult; }
Example to test all conditions of Logical Operators in C#
using System; public class ExampleLogicalOperators { public static void Main(string[] args) { // create truth table for && (conditional AND) operator Console.WriteLine( "{0}\n{1}: {2}\n{3}: {4}\n{5}: {6}\n{7}: {8}\n", "Conditional AND (&&)", "false && false", ( false && false ), "false && true", ( false && true ), "true && false", ( true && false ), "true && true", ( true && true ) ); // create truth table for || (conditional OR) operator Console.WriteLine( "{0}\n{1}: {2}\n{3}: {4}\n{5}: {6}\n{7}: {8}\n", "Conditional OR (||)", "false || false", ( false || false ), "false || true", ( false || true ), "true || false", ( true || false ), "true || true", ( true || true ) ); // create truth table for & (boolean logical AND) operator Console.WriteLine( "{0}\n{1}: {2}\n{3}: {4}\n{5}: {6}\n{7}: {8}\n", "Boolean logical AND (&)", "false & false", ( false & false ), "false & true", ( false & true ), "true & false", ( true & false ), "true & true", ( true & true ) ); // create truth table for | (boolean logical inclusive OR) operator Console.WriteLine( "{0}\n{1}: {2}\n{3}: {4}\n{5}: {6}\n{7}: {8}\n", "Boolean logical inclusive OR (|)", "false | false", ( false | false ), "false | true", ( false | true ), "true | false", ( true | false ), "true | true", ( true | true ) ); // create truth table for ^ (boolean logical exclusive OR) operator Console.WriteLine( "{0}\n{1}: {2}\n{3}: {4}\n{5}: {6}\n{7}: {8}\n", "Boolean logical exclusive OR (^)", "false ^ false", ( false ^ false ), "false ^ true", ( false ^ true ), "true ^ false", ( true ^ false ), "true ^ true", ( true ^ true ) ); // create truth table for ! (logical negation) operator Console.WriteLine( "{0}\n{1}: {2}\n{3}: {4}", "Logical negation (!)", "!false", ( !false ), "!true", ( !true ) ); } // end Main } // end class ExampleLogicalOperators
Calculate compound interest in C#
using System; public class CompoundInterest { public static void Main( string[] args ) { decimal amount; // amount on deposit at end of each year decimal principal = 1000; // initial amount before interest double rate = 0.05; // interest rate // display headers Console.WriteLine( "Year{0,20}", "Amount on deposit" ); // calculate amount on deposit for each of ten years for ( int year = 1; year <= 10; year++ ) { // calculate new amount for specified year amount = principal * ( ( decimal ) Math.Pow( 1.0 + rate, year ) ); // display the year and the amount Console.WriteLine( "{0,4}{1,20:C}", year, amount ); } // end for } // end Main } // end class CompoundInterest
Prefix increment and postfix increment operators in C#
using System; public class IncrementClass { public static void Main( string[] args ) { int c; // demonstrate postfix increment operator c = 5; // assign 5 to c Console.WriteLine( c ); // display 5 Console.WriteLine( c++ ); // display 5 again, then increment Console.WriteLine( c ); // display 6 Console.WriteLine(); // skip a line // demonstrate prefix increment operator c = 5; // assign 5 to c Console.WriteLine( c ); // display 5 Console.WriteLine( ++c ); // increment then display 6 Console.WriteLine( c ); // display 6 again } // end Main } // end class IncrementClass
Addition of two numbers input from the keyboard in C#
using System; public class SumItUp { // Main method begins execution of C# application public static void Main( string[] args ) { int number1; // declare first number to add int number2; // declare second number to add int sum; // declare sum of number1 and number2 Console.Write( "Enter first integer: " ); // prompt user // read first number from user number1 = Convert.ToInt32( Console.ReadLine() ); Console.Write( "Enter second integer: " ); // prompt user // read second number from user number2 = Convert.ToInt32( Console.ReadLine() ); sum = number1 + number2; // add numbers Console.WriteLine( "Sum is {0}", sum ); // display added sum } // end Main } // end class SumItUp
