Few useful tips for C#/.NET
|
1. Nullable Types/Nullable Modifier(?): We cannot directly assign “null” value to “Value-Type”. For this purpose nullable types has been introduced in C# 2.0. using this we can assign null to “Value-Type” variables. For ex: int? num = null; A nullable type has two members: HasValue: It is set to true when the variable contains a non-null value Value: If HasValue is true, Value contains a meaningful value. If HasValue is false, accessing Value will throw a InvalidOperationException. Now, we can check these variables directly for null value like: while(num == null) int? num = null; if(num.HasValue) 2. TryParse():
In C# 2.0, all the numeric primitive types include a static TryParse()method. This method is very similar to the Parse() method, except thatinstead of throwing an exception if the conversion fails, the TryParse() method returns false. It Takes 2 parameters:
i> Data To be Parsed
ii> Resultant variable (output type)
For Ex:
//To parse the input given by the user
int num = 0; int.TryParse(System.Console.ReadLine(), outnum); //if the input is any number then it is assigned to the output parameter num, otherwise not. //now one can use this variable without any need of exception handling, like: 3. Usage of double/decimal: Consider the following statement: Console.WriteLine(6.023231234567891234567244356 * 10E15); //output is : 6.02323123456789E+16 Actually, the C# compiler, by-default takes fraction value as a Double-Type, and a Double Type can keep number with precision of upto 15 significant digits, So, to view/calculate large precised data, we use decimal data type which can keep number with precision upto 29 significant digits. For Ex: // use “m” as suffix for decimal value:Console.WriteLine(6.023231234567891234567244356m * 10E15m); //decimal value
//output is: 60232312345678912.345672443560 Where as a decimal type variable can hold a number having range of 7.9 10^28 but has significant digits 28-29.Also, calculations with decimal are slightly slower )
4. “verbatim string”(@): For Ex: Consider the following line: Console.WriteLine(@” “); will write all the characters on the console window including line breaks, whitepsaces and symbols. |