Skip to main content

Posts

Showing posts from July, 2018

What is the Real World use of Copy Constructor in C#

Copy constructor technique is not provided by .NET, but we can write one by our-self, This type of special constructor will take the paramater as object of its type, If you want create an object for a class with existing object values and only if you want to change some values the copy constructor will come for help Example: We have SalesRep class and we want to move all the reptative values in some set of object then we can re-use this,     class SalesRep     {         public int SalesRepID { get ; set ; }         public string SalesRepAddress { get ; set ; }         public string VisitingDoctor { get ; set ; }          public string DoctorAddress { get ; set ; }     } Writing a normal constructor which picks only the doctor details         public SalesRep( string pVisitingDoctor, string pDoctorAddress)         {             VisitingDoctor = pVisitingDoctor;             DoctorAddress = pDoctorAddress;         }

Implicit and Explicit Conversions in C#

Let's Start by Converting int to long  Example 1:       int  IntValue = 10; long  LongValue; // Converting int to long is easy LongValue = IntValue; // The above code will work as we are converting from small memory size to bigger one Example 2: int IntValue = 10; long LongValue = 1000; // Converting int to long is NOT easy possible IntValue = LongValue; // The above code will NOT work as we are converting from bigger memory size to smaller one, // Even though we are assigning the values to int that is capable of holding Compiler Error: Cannot implicitly convert type 'long' to 'int'. An explicit conversion exists (are you missing a cast?) So how do we convert? here comes the explicit conversion technique, Example 3: int IntValue = 10; long LongValue = 1000; IntValue = ( int )LongValue; This will perfectly work  but explicit conversion has some dangers, we will see what

C# Try Catch & Finally Demystified

One can wonder what can be there to demystify the try catch and finally block, There are some tricky scenarios in this area Lets see what are all that: Ideally Try is used along with Catch, so if any exception arises then it will be get catch in the catch block and based on the  business's preference he / she may want to throw using throw keyword or write in log file or do any other action. The Try Catch Finally works in the following mannaer Step 1: Control Comes inside the try block. Step 2: If the code inside the try executes normal then the control goes to finally block. Step 3: If the code inside the try is throwing error then it will execute the contents of the catch and then go to finally block. Step 4: In finally block thw CLR will free up the resources used in that try block. Step 5: If the function returns the control inside the try block, then also the control will finally comes to finally. Step 6: You cannot return the control from