Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Wednesday, June 3, 2015

Using statement in C#


using:

Using block/statement is used to free unmanaged resources.

Using statement is translated to three parts,
  • Acquisition
  • Usage
  • Disposal
This resource is first acquired, then the usage is enclosed in a try statement with a finally clause. The object then gets disposed in the finally clause.

using (MemoryStream objStream = new MemoryStream())
{
    objStream.WriteTo(Response.OutputStream);
}

this code gets translated to

MemoryStream objStream = new MemoryStream();
try
{
    objStream.WriteTo(Response.OutputStream);
}
finally
{
    if(objStream !=null)
       ((IDisposable)objStream).Dispose();
}


Objects that implement IDisposable can be used in a using statement. Calling Dispose() explicitly (or implicitly via a using statement) can have performance benefits.

"Code that is using a resource can call Dispose() to indicate that the resource is no longer needed. If Dispose() is not called, then automatic disposal eventually occurs as a consequence of garbage collection." - MSDN

In the below code we can observe the following points,
  • If we use using block along a Customer type, it give a compiler error, saying that "type used in a using statement must be implicitly convertible to 'System.IDisposable'".
  • Same if use with Student type, it does not give any error, because it implements System.IDisposable interface.
Sample code -

foreach loop in C#


foreach:

It repeats a group of embedded statements for each element in an array or an object collection. By a collection, we mean any class, struct, or interface that implements the IEnumerable interface.

foreach gives read-only access to the array contents, so we can not change the values of any of the elements.

Only forward iteration is possible in for-each loop.

The condition to work with IEnumerable objects is that the underlying collection must not change while you are accessing it. You can presume that the Enumerable object is a snap shot of the original collection, so if you tries to change the collection while enumerating, it will throw an exception. However the fetched objects in Enumeration is not immutable at all.

Since the variable used in foreach loop is local to the loop block this variable is however not available outside the block.

In the below code we can observe the following points,
  • If we try to modify the foreach iteration variable either primitive type (int) or a user defined class (Customer), we get compile time error.
  • If we try to add/remove any item from the collection, we get run time exception.
  • We can always modify the object properties (Name property in Customer type), which are not immutable.
Sample Code-

Sunday, March 23, 2014

typeof

typeof is an operator, which cannot be overloaded.
Used to obtain the System.Type object for a type.
This operator uses reflection to access the metadata descriptions of the types.
There is only one System.Type object for any given type. This means that for a type T, typeof(T)==typeof(T) is always true. This type cannot be dynamic.

Synatx: typeof(type)
             typeof(unbound-type-name)
             typeof(void)

It returns the System.Type object for the specified type.

[Note: An Unbound-type-name is very similar to a type name except that an unbound-type-name contains generic-dimension-specifiers wherea type-name contains type-argument-lists.]

Examples:
typeof(int);  //System.Int32
typeof(List<int>);  //System.Collections,Generic.List'1[System.Int32]
typefo(Dictionary<,>);  //System.Collections,Generic.Dictionary'2[TKey,TValue]
typeof(void); //System.Void

   The result of typeof(void) is the System.Type object that represents the absence of a type. This special type object is useful in class libraries that allow reflection onto methods in the language, where those methods wish to have a way to represent the return type of any method, including void methods, with an instance of System.Type.

Test:
Employee objEmployee = new Employee();
System.Type t = typeof(objEmployee); //throws error, because typeof only works on types, not on variables.
System.Type t = typeof(Employee) ; //it is fine.

Thursday, April 25, 2013

Converting Csv to DataTable

Steps:
1. First, by using the File class static method ReadAllLines(path), read all the lines from the csv file  to the string array.
2. In the resulting array, first element contains the column names. using the first line, we should create the Data table columns.
3. Other than the first element, all other elements contains the row's data. Using the same we can create the data table rows.

Output

Creating Csv file from DataTable in C#

Steps:
1. Create a DataTable Schema.
2. Fill the created table with some sample data.
3. Create a StringBuilder, by appending all the data, (using comma delimiter)
    a) Create one new line with data table columns.
    b) Create one line for each data table row.
4. Save the StringBuilder to Csv file, using FileStream.

Friday, April 19, 2013

Excel Load To DataTable using OleDb in C#

Here we will try to load Excel sheet  data into the datatable using Jet engine.
First, We need to  Download and install the AccessDatabaseEngine exe from the microsoft web site.

Complete Source Code.

Friday, March 15, 2013

Split the List of objects into Batches using LINQ

There may be certain situations, When we have a number of objects in the list, but we need to split the objects into batches by batch size.

To Do that we can use LINQ, Skip and Take static methods.
Skip : Bypasses a specified number of elements in a sequence and then returns the remaining elements.
Take : Returns a specified number of contiguous elements from the start of a sequence.

Using both these static methods, we can split the list into multiple lists based on the batch size.

While writing the source code, my main intention is to just show how to split the list into batch sizes. So didn't bother about the validations, and other things. Kindly ignore those things.
  1.  First of all creating a Student Class. Which is a template to create the Student objects. ( We can use anonymous types also).
  2.  Then writing a method to create a list of objects for student class. I have just given some random data,  and creating some 23 objects.
  3.  Then writing a method to split the passed list of objects into batches, based on the passed batch size.
  4.  At last calling all the methods from the Main method.
Here i am giving the full source code.
Output:

Sunday, July 29, 2012

Print N numbers without using Loops

In some interviews we may get a question like print certain numbers without using any loops. There are many approaches to accomplish this task. Here i am giving  two of the approaches

1) With recursion 
2) With goto statement.

With Recursion

 void PrintWithRecursion(int fromNumber, int toNumber)
        {
            if (fromNumber <= toNumber)
            {
                Console.Write(fromNumber + " ");
                fromNumber++;
                PrintWithRecursion(fromNumber, toNumber);
            }
        }

With goto statement

void PrintWithGoto(int fromNumber, int toNumber)
        {
        Repeat:
            if (fromNumber <= toNumber)
            {
                Console.Write(fromNumber + " ");
                fromNumber++;
                goto Repeat;
            }
            Console.Read();
        }


Complete Source code:


output:





Thursday, November 10, 2011

File copying using FTP

Normal FTP file copying process using built in classes provided System.Net NameSpace.
The code is as follows, do not forget to add System.Net namespace.

Wednesday, November 9, 2011

Swapping two integers

Swapping Two Integers using different methods.
     1) Using Temporary variable
     2) Using Arithmetic Operators
     3) Using EX-OR operator

 Here is the complete source code.

Output it as shown Below:

Tuesday, November 8, 2011

DataRowState

DataRowState : Its a state corresponding to each row in DataTable.
Consider the following scenario, we have a set of records in DB and from the User Interface we need to provide the facility for user to update any existing records or to add any new records. But, this set of changed records need to send to the DB all at once (i.e for example on a Button Click event), Till that time we need to retain all the records at our page itself. and user also have an option to cancel these changes.
So, while sending all the records to DB at once , we need to find a way to check which row is to be inserted , and which row need to be updated in DB, one option is to maaintain one more column in the table as flag, but its very difficult to maintain these flags. another option is to take the advantage of the DataRowState (if we assume records will be maitained in the DataTable). Each row will be having a State (like Added, Unchanged, Modified etc..), using this States we can easily find out which row should be saved and which row should be updated.
DataRowState is very much useful in this kind of scenarios.
First we will look at the different states present in DataRowState,
Added The row has been added to a DataRowCollection, and AcceptChanges has not been called.
Modified The row has been modified and AcceptChanges has not been called.
UnChanged The row has not changed since AcceptChanges was last called.
Detached The row has been created but is not part of any DataRowCollection. A DataRow is in this state immediately after it has been created and before it is added to a collection, or if it has been removed from a collection.
Deleted The row was deleted using the Delete method of the DataRow.
The below is the example with the all states.
The output will be as follws:
In the above output we can see that , at last the changes are canceled , but still one of the row is not exist. this is because it has got removed(not deleted). we cannot get the records back once we use Remove. but if we use Delete , still we can get our records back.