Posts

Showing posts from 2010

Generics

Generics Generics is a form of abstraction in developing code. Instead of writing a function or a class for a particular type, it can be written generally to use any type. When an instance of the generic class is instantiated, the type is specified. Generics was introduced in .NET Framework 2.0. MS recommends using Generics functions and classes instead of non-generic. Generic namespace is under the System.Collections. Example: Say you want to swap two integers, strings etc. In the non-generic form, you would create 2 seperate functions, one for Integers and one for Strings.. to eliminate this duplication for the same functionality, we can use the generic methods and classes. public void Swap ( a, b) { T temp; temp=a; a=b; b=temp; } We can call the above generic function for either int or string. Swap (int a, int b); Swap (string s1, string s2); How do you set default values ??? C# provides a keyword called "default" which 1) for value types, the default value is 0.2) for re...

System.Environment.NewLine

C# offers the System.Environment.NewLine which acts as "\r\n". The advantage of using the NewLine property is that it is platform sensitive. In Windows, the carriage is represented as "\r\n" where as in Linux, it is "\n". Use System.Environment.NewLine property so that it works correctly on any platform. Example: string str= "Hello" + System.Environment.NewLine + "Sree";

Structs and Constructors.

Did you know that the Value Types ( Structs) cannot have parameterless Constructors? For example the code below generates a compilation error: "Structs cannot contain explicit parameterless constructors" internal struct StructExample { public StructExample() { } } However, you can define parameterless constructors in structs by specifying "static" keyword. internal struct StructExample { static StructExample() { } } No Access modifier is specified, because we "Cannot specify any access modifier for a static Constructor". By Default, they have private access modifier.