Static Constructors

A static constructor is used to initialize any static data, or to perform a particular action that needs performed once only. It is called automatically before the first instance is created or any static members are referenced.

Static constructors have the following properties:

  • A static constructor does not take access modifiers or have parameters.
  • A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced. It depends on CLR Version.
  • A static constructor cannot be called directly.
  • Cannot have overloaded versions of static constructors.
  • The user has no control on when the static constructor is executed in the program.
  • A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.
  • Static constructors are also useful when creating wrapper classes for unmanaged code, when the constructor can call the LoadLibrary method.
Advertisements

Linq Single vs SingleOrDefault vs First vs FirstOrDefault :

Single() SingleOrDefault() First() FirstOrDefault()
Description Returns a single, specific element of a sequence Returns a single, specific element of a sequence, or a default value if that element is not found Returns the first element of a sequence Returns the first element of a sequence, or a default value if no element is found
Exception thrown when There are 0 or more than 1 elements in the result There is more than one element in the result There are no elements in the result Only if the source is null (they all do this)
When to use If exactly 1 element is expected; not 0 or more than 1 When 0 or 1 elements are expected When more than 1 element is expected and you want only the first When more than 1 element is expected and you want only the first. Also it is ok for the result to be empty

Performance Enhancer – AddRange instead of foreach-add for collections copy!

If the source collection needs to be copied to destination list, its better to use addRange instead of foreach-add while copying. (Mere assigning source collection to destination collection is not what intended as it won’t create a new memory for destination list.)
Say I have a source list of students – Student List & I need to copy only Student ids to Destination list- IdsList.
The code can be –
IdsList = new List();
StudentList.ForEach(a=> IdsList.Add(a.Id));

The above code takes some extra oeverhead wrt runtime allocation.
Instead we can go with
IdsList = new List();
IdsList.AddRange(StudentList.Select(a=>a.Id));

In the second process, it allocates the memory for entire IdsList onetime & copies at once. where as in first case, for every iteration in ForEach, it allocates memory for each single item while adding to IdsList which is an additional overhead if it is mere copy kinda.

Difference btw implicit and explicit implemention of interfaces

When a class inherited from a interfaces, it has to implement that interface. So usually we go for implicit implementation.
Here question comes..then when do we go for explicit implementation ??
Cases:
1.when we inherit from more than an interface, which has common elements. Ie, with same signature.so in order to differentiate, we go for explicit implementation, where explicitly specify the interface name before elements.
2.when we want to restrict the access of interface members in implementing classes.

Parse, Convert.To Pros & Cons :


Parse
Convert To
Try Parse
1) Doesn’t Handles null values. If input is null,It will throwArgumentNullException. 1) Handles null,doesn’t throw exception.
Instead it returns default value
1)Handles null,doesn’t throw exception.Instead it outs default value.
2) If input other than expected type, it will throwFormatException. 2)If input other than expected type, it will throw FormatException . 2) If input other than expected Type,It outs default value instead of format exception
3) If memory range voilates, it will throw OverflowException 3)If memory range voilates, it will throw OverflowException 3) If Memory range voilates, it outs default instead of OverFlowException
So TryParse is better to use.
But if you want to make sure of few customised validations uniformly across the code like
Ex : The default of string is null, the default of DateTime is 1/1/1. so in order to even default values to be on safer side, can have the Extension method to override the default values
string – string.Empty
DateTime – Current DateTime
namespaceExampleForConvertTo
{
publicpartialclassForm1: Form
{
publicForm1()
{
InitializeComponent();
}
protectedoverridevoidOnLoad(EventArgse)
{
base.OnLoad(e);
strings = default(string);//Null
inta = 0;
stringd = null;
a = d.ConvertTo<int>();//0
d = “S”;
a = d.ConvertTo<int>();//0
d = “9”;
a = d.ConvertTo<int>();//9
}
}
publicstaticclassMethodExtensions
{
publicstaticT ConvertTo<T>(thisobjectval)
{
try
{
objecttVal = Convert.ChangeType(val, typeof(T));
if(tVal == null) thrownewException();
else
{
return(T)tVal;
}
}
catch
{
return(T)((typeof(T) == typeof(string)) ? (object)string.Empty :
((typeof(T) == typeof(DateTime)) ? (object)(DateTime.Now) : (object)default(T))
);
}
}
}

}

HashTable vs Dictionary

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;

//   ———————————————————————————————————————
//  Differences
//  On HashTable, we cannot apply KeyValuePair enumeration
//  On HashTable , if give the Unknown Key, it will return null whereas On Dictionary, it will throw runtime error if we try to access the Value
//            ***If you use indexers to get a value out of a HashTable, the HashTable will successfully return null for a non-existent item, whereas the Dictionary will throw an error if you try accessing a item using a indexer which does not exist in the Dictionary
//  On HashTable, Only way to access value is by passing the Key(not ViceVersa operation succeeds)
//   ———————————————————————————————————————

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
Dictionary myDict = new Dictionary();
Hashtable objHashTable = new Hashtable();
public Form1()
{
InitializeComponent();
LoadDict();
MessageBox.Show(“Hash Results”);
LoadHash();
}
private void LoadDict()
{
myDict.Add(2, “Anu”);
myDict.Add(1, “Shalini”);
myDict.Add(3, “Archu”);
foreach (KeyValuePair v in myDict)
{
MessageBox.Show(string.Concat(v.Key, v.Value));
}
//for (int i = 0; i < myDict.Count; i++)
//{
//    MessageBox.Show(string.Concat(myDict[i]));
//}
}
private void LoadHash()
{
objHashTable.Add(2, “Anu”);
objHashTable.Add(1, “Shalini”);
objHashTable.Add(3, “Archu”);
objHashTable.Add(“bujji”, 4);
//foreach (KeyValuePair v in objHashTable)
//{
//    MessageBox.Show(string.Concat(v.Key,v.Value));
//}
for (int i = 0; i < objHashTable.Count; i++)
{
MessageBox.Show(string.Concat(objHashTable[i]));
}
//MessageBox.Show(objHashTable[“Shalini”].ToString());
MessageBox.Show(objHashTable[“bujji”].ToString());
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
this.Close();
}

}
}

By Ref and By Value

usingSystem;
usingSystem.Collections.Generic;
usingSystem.ComponentModel;
usingSystem.Data;
usingSystem.Drawing;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Windows.Forms;

namespaceWindowsFormsApplication1
{
publicclassDepartmemt
{
publicintDeptNo { get; set; }
publicstringDepartmentName { get; set; }
}


publicclassEmployee
{
publicintEmpNo { get; set; }
publicstringEmpName { get; set; }
publicDepartmemtEmpDepartment { get; set; }
}
publicpartialclassForm1: Form
{
publicForm1()
{
InitializeComponent();
Loading();
}
privatevoidLoading()
{
//New Memory Created in Heap and pointed by empObj1 in Stack
//Lets assume that empObj1 contains value(Address)->#1
Employeeempobj1 = newEmployee()
{ EmpNo = 1, EmpName = “Shalini”, EmpDepartment = newDepartmemt()
{ DeptNo = 1, DepartmentName = “.Net”} };
//No New Memory is created in Heap, instead a memory is created in stack for storing address.
//So empobj2 also contains #1
Employeeempobj2 = empobj1;
Employeeempobj3 = empobj1;
ChangeEmpDetails(empobj1);
// Values are not effected by below statement, because the following function is not working directly on #1
MessageBox.Show(empobj1.EmpName);//Output : Shalini
AssignEmpDetails(empobj2);
// Values are effected by below statement, because the following function is working directly on #2
MessageBox.Show(empobj2.EmpName);//Output : Anu

ChangeEmpDetailsThrRef(refempobj3);
// Values are effected by below statement, because the following function is working directly on variable rather than on value ie.. #1
MessageBox.Show(empobj3.EmpName);//Output : Anu
}
privatevoidChangeEmpDetails(EmployeeobjEmp)
{
//Here we recieved the #1 as input – objEmp
//New Memory Created in Heap and pointed by emp in Stack
//Lets assume that emp contains value(Address)->#2
Employeeemp = newEmployee();
emp.EmpNo = 2;
emp.EmpName = “Anu”;
emp.EmpDepartment = newDepartmemt() { DeptNo = 2, DepartmentName = “Oracle”};
//We replaced the objEmp with #2
objEmp = emp;
}


privatevoidAssignEmpDetails(EmployeeobjEmp)
{
//Here we recieved the #1 as input in objEmp
//if we refer objEmp means..we are referring to previously created memory
objEmp.EmpNo = 2;
objEmp.EmpName = “Anu”;
objEmp.EmpDepartment = newDepartmemt() { DeptNo = 2, DepartmentName = “Oracle”};
}


privatevoidChangeEmpDetailsThrRef(refEmployeeobjEmp)
{
//Here we recieved the newly created(from outside) memory
//New Memory Created in Heap and pointed by emp in Stack
//Lets assume that emp contains value(Address)->#3
Employeeemp = newEmployee();
emp.EmpNo = 2;
emp.EmpName = “Anu”;
emp.EmpDepartment = newDepartmemt() { DeptNo = 2, DepartmentName = “Oracle”};
//We replaced the objEmp with #3
objEmp = emp;
}

}
}