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

Saturday, 17 November 2012

C#.Net Interview Question and Answers

C#.Net Interview Question and Answers
1. What is C#?
C# (pronounced "C sharp") is a simple, modern, object-oriented, and type-safe programming language.
It will immediately be familiar to C and C++ programmers.
C# combines the high productivity of Rapid Application Development (RAD) languages.
2. What are the types of comment in C#?
There are 3 types of comments in C#.
Single line (//)
Mul

ti (/* */)
Page/XML Comments (///).
3. What are the namespaces used in C#.NET?
Namespace is a logical grouping of class.
using System;
using System.Collections.Generic;
using System.Windows.Forms;
4. What are the characteristics of C#?
There are several characteristics of C# are :
Simple
Type safe
Flexible
Object oriented
Compatible
Consistent
Interoperable
Modern
5. How does C# differ from C++?
C# does not support #include statement. It uses only using statement.
In C# , class definition does not use a semicolon at the end.
C# does not support multiple code inheritance.
Casting in C# is much safer than in c++.
In C# switch can also be used on string values.
Command line parameters array behave differently in C# as compared to C++.
6. What are the basic concepts of object oriented programming?
It is necessary to understand some of the concepts used extensively in object oriented programming.These include
Objects
Classes
Data abstraction and encapsulation
Inheritance
Polymorphism
Dynamic Binding
Message passing.
7. Can you inherit multiple interfaces?
Yes. Multiple interfaces may be inherited in C#.
8. What is inheritance?
Inheritance is deriving the new class from the already existing one.
9. Define scope?
Scope refers to the region of code in which a variable may be accessed.
10. What is the difference between public, static and void?
public :The keyword public is an access modifier that tells the C# compiler that the Main method is accessible by anyone.
static :The keyword static declares that the Main method is a global one and can be called without creating an instance of the class. The compiler stores the address of the method as the entry point and uses this information to begin execution before any objects are created.
void : The keyword void is a type modifier that states that the Main method does not return any value.
11. What are the modifiers in C#?
Abstract
Sealed
Virtual
Const
Event
Extern
Override
Readonly
Static
New
12. What are the types of access modifiers in C#?
Access modifiers in C# are :
public
protect
private
internal
internal protect
13. What is boxing and unboxing?
Implicit conversion of value type to reference type of a variable is known as BOXING, for example integer to object type conversion.
Conversion of reference type variable back to value type is called as UnBoxing.
14. What is object?
An object is an instance of a class. An object is created by using operator new. A class that creates an object in memory will contain the information about the values and behaviours (or methods) of that specific object.
15. Where are the types of arrays in C#?
Single-Dimensional
Multidimensional
Jagged arrays.
16. What is the difference between Object and Instance?
An instance of a user-defined type is called an object. We can instantiate many objects from one class.
An object is an instance of a class.
17. Define destuctors?
A destructor is called for a class object when that object passes out of scope or is explicitly deleted.A destructors as the name implies is used to destroy the objects that have been created by a constructors.Like a constructor , the destructor is a member function whose name is the same as the class name but is precided by a tilde.
18. What is the use of enumerated data type?
An enumerated data type is another user defined type which provides a way for attaching names to numbers thereby increasing comprehensibility of the code. The enum keyword automatically enumerates a list of words by assigning them values 0,1,2, and so on.
19. Define Constructors?
A constructor is a member function with the same name as its class. The constructor is invoked whenever an object of its associated class is created.It is called constructor because it constructs the values of data members of the class.
20. What is encapsulation?
The wrapping up of data and functions into a single unit (called class) is known as encapsulation. Encapsulation containing and hiding information about an object, such as internal data structures and code.
21. Does c# support multiple inheritance?
No,its impossible which accepts multi level inheritance.
22. What is ENUM?
Enum are used to define constants.
23. What is a data set?
A DataSet is an in memory representation of data loaded from any data source.
24. What is the difference between private and public keyword?
Private : The private keyword is the default access level and most restrictive among all other access levels. It gives least permission to a type or type member. A private member is accessible only within the body of the class in which it is declared.
Public : The public keyword is most liberal among all access levels, with no restrictions to access what so ever. A public member is accessible not only from within, but also from outside, and gives free access to any member declared within the body or outside the body.
25. Define polymorphism?
Polymorphism means one name, multiple forms. It allows us to have more than one function with the same name in a program.It allows us to have overloading of operators so that an operation can exhibit different behaviours in different instances.
26. What is Jagged Arrays?
A jagged array is an array whose elements are arrays.
The elements of a jagged array can be of different dimensions and sizes.
A jagged array is sometimes called an array–of–arrays.
27. what is an abstract base class?
An abstract class is a class that is designed to be specifically used as a base class. An abstract class contains at least one pure virtual function.
28. How is method overriding different from method overloading?
When overriding a method, you change the behavior of the method for the derived class. Overloading a method simply involves having another method with the same name within the class.
29. What is the difference between ref & out parameters?
An argument passed to a ref parameter must first be initialized. Compare this to an out parameter, whose argument does not have to be explicitly initialized before being passed to an out parameter.
30. What is the use of using statement in C#?
The using statement is used to obtain a resource, execute a statement, and then dispose of that resource.
31. What is serialization?
Serialization is the process of converting an object into a stream of bytes.
De-serialization is the opposite process of creating an object from a stream of bytes.
Serialization / De-serialization is mostly used to transport objects.
32. What are the difference between Structure and Class?
Structures are value type and Classes are reference type
Structures can not have contractors or destructors.
Classes can have both contractors and destructors.
Structures do not support Inheritance, while Classes support Inheritance.
33. What is difference between Class And Interface?
Class : is logical representation of object. It is collection of data and related sub procedures with defination.
Interface : is also a class containg methods which is not having any definations.Class does not support multiple inheritance. But interface can support.
34. What is Delegates?
Delegates are a type-safe, object-oriented implementation of function pointers and are used in many situations where a component needs to call back to the component that is using it.
35. What is Authentication and Authorization?
Authentication is the process of identifying users. Authentication is identifying/validating the user against the credentials (username and password).
Authorization performs after authentication. Authorization is the process of granting access to those users based on identity. Authorization allowing access of specific resource to user.
36. What is a base class?
A class declaration may specify a base class by following the class name with a colon and the name of the base class. omitting a base class specification is the same as deriving from type object.
37. Can “this” be used within a static method?
No ‘This’ cannot be used in a static method. As only static variables/methods can be used in a static method.
38. What is difference between constants, readonly and, static ?
Constants: The value can’t be changed.
Read-only: The value will be initialized only once from the constructor of the class.
Static: Value can be initialized once.
39. What are the different types of statements supported in C#?
C# supports several different kinds of statements are
Block statements
Declaration statements
Expression statements
Selection statements
Iteration statements
Jump statements
Try catch statements
Checked and unchecked
Lock statement
40. What is an interface class?
It is an abstract class with public abstract methods all of which must be implemented in the inherited classes.
41. what are value types and reference types?
Value types are stored in the Stack.
Examples : bool, byte, chat, decimal, double, enum , float, int, long, sbyte, short, strut, uint, ulong, ushort.

Reference types are stored in the Heap.
Examples : class, delegate, interface, object, string.
42. What is the difference between string keyword and System.String class?
String keyword is an alias for Syste.String class. Therefore, System.String and string keyword are the same, and you can use whichever naming convention you prefer. The String class provides many methods for safely creating, manipulating, and comparing strings.
43. What are the two data types available in C#?
Value type
Reference type
44. What are the different types of Caching?
There are three types of Caching :
Output Caching: stores the responses from an asp.net page.
Fragment Caching: Only caches/stores the portion of page (User Control)
Data Caching: is Programmatic way to Cache objects for performance.
45. What is the difference between Custom Control and User Control?
Custom Controls are compiled code (Dlls), easier to use, difficult to create, and can be placed in toolbox. Drag and Drop controls. Attributes can be set visually at design time. Can be used by Multiple Applications (If Shared Dlls), Even if Private can copy to bin directory of web application add reference and use. Normally designed to provide common functionality independent of consuming Application.

User Controls are similar to those of ASP include files, easy to create, can not be placed in the toolbox and dragged - dropped from it. A User Control is shared among the single application files.
46. What is methods?
A method is a member that implements a computation or action that can be performed by an object or class. Static methods are accessed through the class. Instance methods are accessed through instances of the class.
47. What is fields?
A field is a variable that is associated with a class or with an instance of a class.
48. What is events?
An event is a member that enables a class or object to provide notifications. An event is declared like a field except that the declaration includes an event keyword and the type must be a delegate type.
49. What is literals and their types?
Literals are value constants assigned to variables in a program. C# supports several types of literals are
Integer literals
Real literals
Boolean literals
Single character literals
String literals
Backslash character literals
50. What is the difference between value type and reference type?
Value types are stored on the stack and when a value of a variable is assigned to another variable.
Reference types are stored on the heap, and when an assignment between two reference variables occurs.
51. What are the features of c#?
C# is a simple and powerful programming language for writing enterprise edition applications.
This is a hybrid of C++ and VB. It retains many C++ features in the area statements,expressions, and operators and incorporated the productivity of VB.
C# helps the developers to easily build the web services that can be used across the Internet through any language, on any platform.
C# helps the developers accomplishing with fewer lines of code that will lead to the fewer errors in the code.
C# introduces the considerable improvement and innovations in areas such as type safety,versioning. events and garbage collections.
52. What are the types of errors?
Syntax error
Logic error
Runtime error
53. What is the difference between break and continue statement?
The break statement is used to terminate the current enclosing loop or conditional statements in which it appears. We have already used the break statement to come out of switch statements.
The continue statement is used to alter the sequence of execution. Instead of coming out of the loop like the break statement did, the continue statement stops the current iteration and simply returns control back to the top of the loop.
54. Define namespace?
The namespace are known as containers which will be used to organize the hierarchical set of .Net classes.
55. What is a code group?
A code group is a set of assemblies that share a security context.
56. What are sealed classes in C#?
The sealed modifier is used to prevent derivation from a class. A compile-time error occurs if a sealed class is specified as the base class of another class.
57. What is the difference between static and instance methods?
A method declared with a static modifier is a static method. A static method does not operate on a specific instance and can only access static members.

A method declared without a static modifier is an instance method. An instance method operates on a specific instance and can access both static and instance members. The instance on which an instance method was invoked can be explicitly accessed as this. It is an error to refer to this in a static method.
58. What are the different types of variables in C#?
Different types of variables used in C# are :
static variables
instance variable
value parameters
reference parameters
array elements
output parameters
local variables
59. What is meant by method overloading?
Method overloading permits multiple methods in the same class to have the same name as long as they have unique signatures. When compiling an invocation of an overloaded method, the compiler uses overload resolution to determine the specific method to invoke
60. What is parameters?
Parameters are used to pass values or variable references to methods. The parameters of a method get their actual values from the arguments that are specified when the method is invoked. There are four kinds of parameters: value parameters, reference parameters, output parameters, and parameter arrays.
61. Is C# is object oriented?
YEs, C# is an OO langauge in the tradition of Java and C++.
62. What is the difference between Array and Arraylist?
An array is a collection of the same type. The size of the array is fixed in its declaration. A linked list is similar to an array but it doesn’t have a limited size.
63. What are the special operators in C#?
C# supports the following special operators.
is (relational operator)
as (relational operator)
typeof (type operator)
sizeof (size operator)
new (object creator)
.dot (member access operator)
checked (overflow checking)
unchecked (prevention of overflow checking)
64. What is meant by operators in c#?
An operator is a member that defines the meaning of applying a particular expression operator to instances of a class. Three kinds of operators can be defined: unary operators, binary operators, and conversion operators. All operators must be declared as public and static.
65. What is a parameterized type?
A parameterized type is a type that is parameterized over another value or type.
66. What are the features of abstract class?
An abstract class cannot be instantiated, and it is an error to use the new operator on an abstract class.
An abstract class is permitted (but not required) to contain abstract methods and accessors.
An abstract class cannot be scaled.
67. What is the use of abstract keyword?
The modifier abstract is a keyword used with a class, to indicate that this class cannot itself have direct instances or objects, and it is intended to be only a 'base' class to other classes.
68. What is the use of goto statement?
The goto statement is also included in the C# language. This goto can be used to jump from inside a loop to outside. But jumping from outside to inside a loop is not allowed.
69. What is the difference between console and window application?
A console application, which is designed to run at the command line with no user interface.
A Windows application, which is designed to run on a user’s desktop and has a user interface.
70. What is the use of return statement?
The return statement is associated with procedures (methods or functions). On executing the return statement, the system passes the control from the called procedure to the calling procedure. This return statement is used for two purposes :
to return immediately to the caller of the currently executed code
to return some value to the caller of the currently executed code.
71. What is the difference between Array and LinkedList?
Array is a simple sequence of numbers which are not concerned about each others positions. they are independent of each others positions. adding,removing or modifying any array element is very easy. Compared to arrays ,linked list is a comlicated sequence of numbers.
72. Does C# have a throws clause?
No, unlike Java, C# does not require the developer to specify the exceptions that a method can throw.
73. Does C# support a variable number of arguments?
Yes, uisng the params keyword. The arguments are specified as a list of arguments of a specific type.
74. Can you override private virtual methods?
No, private methods are not accessible outside the class.
75. What is a multi cast delegates?
It is a delegate that points to and eventually fires off several methods.

Thursday, 28 June 2012

Call Page Method from JavaScript

Call Page Method from JavaScript



Write Page Method that You want to call (Method Must be Static):

public partial class PageMethod : System.Web.UI.Page
{
   [System.Web.Services.WebMethod()]
    public static string GetMenuItem()
    {
        StringBuilder sb = new StringBuilder();
        sb.Append(“<ul>”);
        sb.AppendFormat(“<li>{0}</li>”,”First”);
        sb.AppendFormat(“<li>{0}</li>”, “Second”);
        sb.AppendFormat(“<li>{0}</li>”, “Third”);
sb.AppendFormat(“<li>{0}</li>”, “Forth”);
        sb.AppendFormat(“<li>{0}</li>”, “Fifth”);
        sb.Append(“</ul>”);
        return sb.ToString();
    }
}


Write JavaScipt to call Page Method :



    <script type=”text/javascript” language=”javascript”>
        function CallWebServiceMethod() {
        PageMethods.GetMenuItem(GetMenuItemComplete, errormethod);
        }

       function GetMenuItemComplete(val) {   /// Called When page method execute successfully
            $get(“divItem”).innerHTML = val;
        }

        function errormethod(val) {    ///  called when error occurs in execution
        alert(“Error” + val)
        }
    </script>


At last Write HTML for display result :


<body onload=”CallWebServiceMethod();”>
    <form id=”form1? runat=”server”>
    <asp:ScriptManager ID=”ScriptManager1? EnablePageMethods=”true” runat=”server”>
/// Bold written Attribute required for calling Page  method
    </asp:ScriptManager>
    <div id=”divItem”>
    </div>
    </form>
</body>

SESSION IN JAVASCRIPT


Session in Javascript



<script type=”text/javascript”>
 //To set Session
function Setsession() {
    if (window.sessionStorage) {
       sessionStorage.setItem(“key1″, document.getElementById(‘<%= Write.ClientID %>’).value);               
    }
}

//To get Session
 
function GetSession() {
     if (window.sessionStorage) {
         document.getElementById(‘<%= Get.ClientID %>’).value = sessionStorage.getItem(“key1″);
      }
}


</script>



To get Session Value using javascript

 <script type=”text/javascript”>
var session = '<%= Session["VALUE"] %>'; 

</script> 

Saturday, 11 February 2012

How to create Image Gallery in asp.net 3.5


Hi
When I was creating Image gallery in asp.net 2.0 using Datalist control, it was taking so much time. But in asp.net 3.5 and 4.0, Microsoft added the ListView control. Using this control we can create within few minute very nice image galleries.
It is the totally template based control like repeater control. It has 11 templates to customize.
Using listview and datapager control we can create very nice image gallery with paging functionality.
Here is no need to write the custom coding for paging functionality.
We can do like this
Step1: Create the database table like this

Step2: take the listview and Datapager control and arrange the HTML code like this
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style type="text/css">
.main{
float:left;
padding:0px;
margin:0px;
width:100%;
}
.imges{
float:left;
padding:0px;
margin:0px;
width:100%;
}
.numbers{
float:left;
margin:0px;
padding:0px;
margin-left:60px;
}
.ProductList Li
{
display :inline;
float:left;
margin-left:25px;
margin-bottom:25px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div class="main">
<div class="imges">
<h3>Students</h3>
<asp:ListView ID="ListView1" runat="server">
<LayoutTemplate>
<ul class="ProductList">
<asp:PlaceHolder runat="server" ID="itemPlaceholder"></asp:PlaceHolder>
</ul>
</LayoutTemplate>
<ItemTemplate>
<li><asp:Image ID="Img1" ImageUrl=’<%#Eval("Image")%>’ runat="server"
Height="200px" Width="150px" /><br /><%#Eval("StudentName")%></li>
</ItemTemplate>
<EmptyItemTemplate>
<div>
Sorry! No Item found found.
</div>
</EmptyItemTemplate>
</asp:ListView>
</div>
<div class="numbers">
<asp:DataPager ID="DataPager1" PageSize="6" PagedControlID="ListView1"
runat="server" onprerender="DataPager1_PreRender">
<Fields>
<asp:NumericPagerField />
</Fields>
</asp:DataPager>
</div>
</div>
</form>
</body>
</html>
Step3:Write the code In code behind like this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
fillData();
}
protected void fillData()
{
using (SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=Test;Integrated Security=True"))
{
//for better performance write the store procedure
using (SqlCommand cmd = new SqlCommand("Select StudentName,Image from tblStudent", con))
{
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
ListView1.DataSource = dt;
ListView1.DataBind();
}
}
}
}
protected void DataPager1_PreRender(object sender, EventArgs e)
{
fillData();
}
}

Monday, 16 January 2012

How to populate month name in DropDownList in ASP.NET


In order to populate the month name in the DropDownList, you can use below code snippet.

DropDownList code
<asp:DropDownList ID="dropDown1" runat="server"></asp:DropDownList>


Namespace to use
using System.Globalization;


Code behind
DateTimeFormatInfo info = DateTimeFormatInfo.GetInstance(null);

        for (int i = 1; i < 13; i++)

        {

            //Response.Write(info.GetAbbreviatedMonthName(i) + "<br />");

            dropDown1.Items.Add(new ListItem(info.GetMonthName(i), i.ToString()));

        }


In the above code, commented code shows how to write abbreviated month name too, so in case you do not want to show the full month name in the dropdown, use GetAbbreviatedMonthName method.

Friday, 30 December 2011

Copy of Session Object

Many times we try to make copy of session object, but in case when we are modifying copied object we might noticed that session object gets updated automatically, the reason is both copied object and session object are pointing to same location, even if you tried to use "new" operator while creating object.

Scenario
Let say you have Member Class as mentioned under
public class Member{


public string FirstName { get; set; }
        public string LastName { get; set; }
}


Problem:
Member objMember = new Member();
objMember.FirstName = "Sachin";
objMember.LastName = "Tendulkar";

Then try to save object in Session
Session["MemberObj"] = objMember;

This method will work good till we are just accessing object from session, but in case if we try to update object created from session it will update value of session also.

That is,
Member newMember = new Member(); //Even though object is created using "new" keyword.
newMember = (Member) Session["MemberObj"];
newMember.FirstName = "Kapil"; //This will update session FirstName also.


Solution:
To make copies of session you need to create a clone method in class.

In above class create a method clone, to support copy of session.


public class Member{


public string FirstName { get; set; }
        public string LastName { get; set; }


public Member clone()
{
   Member cloneMember = new Member();
       cloneMember.FirstName = this.FirstName;
   cloneMember.LastName = this.LastName;
}
}

Now, while accessing session object, you can call clone method to make copy of session.

Member newMember = new Member();
newMember = ((Member) Session["MemberObj"]).clone();

now if you try to modify object copied from session, will not update session object.
newMember.FirstName = "Kapil"; //Will not update session FirstName

C# Jagged Array Examples

You need to evaluate jagged arrays in your C# programs. You have several rows of data, such as integers, and want to store them together in a single data structure. Jagged arrays are ideal for this, and this document has some examples and discussion, with code in the C# programming language.

Example

Here we see some example code that shows you how to use jagged arrays in different ways. The following code is a short but complete program you can run in a console project. It creates an array and sets values in it, then prints out the result at the end.
Example jagged array program [C#]

using System;

class Program
{
    static void Main()
    {
 // Declare local jagged array with 3 rows.
 int[][] jagged = new int[3][];

 // Create a new array in the jagged array, and assign it.
 jagged[0] = new int[2];
 jagged[0][0] = 1;
 jagged[0][1] = 2;

 // Set second row, initialized to zero.
 jagged[1] = new int[1];

 // Set third row, using array initializer.
 jagged[2] = new int[3] { 3, 4, 5 };

 // Print out all elements in the jagged array.
 for (int i = 0; i < jagged.Length; i++)
 {
     int[] innerArray = jagged[i];
     for (int a = 0; a < innerArray.Length; a++)
     {
  Console.Write(innerArray[a] + " ");
     }
     Console.WriteLine();
 }
    }
}

Output

"1 2"
"0"
"3 4 5"
Description. It declares a jagged array. The word 'jagged' doesn't even exist in the C# language, meaning that you don't need to use this word in your code. Jagged is just a descriptive variable name I use.
Initializations used. It initializes some values in the jagged array. There are lots of square brackets. This is very different from a 2D array, which uses commas instead of pure brackets.
Assigning jagged arrays. It assigns an array at the second index. Above you should see that indexes in the array are assigned to new int[] arrays. This is because the jagged array only allocates the list of empty references to arrays at first. You have to make your own arrays to put in it. We see the array initializer syntax here, which is less verbose than some other ways.
Looping over jagged arrays. You will want to examine each item in the jagged array. We must call Length first on the array of references, and then again on each inner array. The Console calls above are just for the example.
Two-dimensional (2D)

2D arrays

Here we will look at how you can choose between jagged arrays and 2D arrays. First, ask yourself the question: will every row in my collection have the same number of elements? If so, you can consider 2D arrays, but often you have varying numbers of elements.
Performance notes. Second, jagged arrays are faster and have different syntax. They are faster because they use the "newarr", vector IL calls internally. The boost is because they are optimized for starting at 0 indexes. Here is some code I compared in IL Disassembler.
Method that is reflected for MSIL test [C#]

private static void CompareIL()
{
    int[,] twoD = new int[1, 1]; // 1 x 1 array

    twoD[0, 0] = 1;

    int[][] jag = new int[1][];

    jag[0] = new int[1];
    jag[0][0] = 1; // 1 x 1 jagged array
}
Jagged array intermediate language in Visual StudioChoosing the syntax. Whichever array type you choose, don't select it because of the syntax. It is important to know that the pairs of brackets indicate "jagged," and the comma in the brackets means "2D".
Separate rows in arrays. You can allocate different arrays for each row in jagged arrays separately, which means your program must use 1D arrays in parts.

Parameters

You can use the type of the jagged array in method signatures in the C# language to use jagged arrays as parameters. You can use the same syntax as we saw above. They will be passed as references, which is important because it eliminates most copying. Only the reference is copied on each function call.
Performance optimization

Benchmark

The .NET runtime has optimizations for this specific case, and for some reason the 2D array cannot take advantage of them. My opinion is that you should always use jagged arrays when possible. They have substantial optimizations in the intermediate language level.
2D array code benchmarked [C#]

// 2D array of 100 x 100 elements.
for (int a = 0; a < 100; a++)
{
    for (int x = 0; x < 100; x++)
    {
 int c = a1[a, x];
    }
}

Jagged array code benchmarked [C#]

// Jagged array of 100 x 100 elements.
for (int a = 0; a < 100; a++)
{
    for (int x = 0; x < 100; x++)
    {
 int c = a2[a][x];
    }
}

Results

2D array looping:      4571 ms 
Jagged array looping:  2864 ms  [faster]

Summary

We saw how you can use jagged arrays in your C# programs. Jagged arrays are fast and easy to use once you learn the slightly different syntax. Prefer them to 2D arrays when performance is a consideration, and they are not more complex more to use. Investigating IL can be useful for understanding .NET internals.

Thursday, 29 December 2011

C# Lambda Expression

You want to use lambda expressions in the C# programming language, allowing functions to be used as data such as variables or fields. The lambda expression syntax uses the => operator and this specifies how the parameters and statement body of the anonymous function instance are separated, and provides a formal name to the environment variables. Here we look at lambda expressions.Lambda expression syntax
Tip: Lambda expressions use the token => in an expression context.

Example

This program demonstrates how you can insert lambda expressions and other anonymous functions into a C# method. The source text uses the => operator, which is a syntax for separating the parameters to a method from the statements in the method's body.
The => operator can be read as "goes to" and it is always used when declaring a lambda expression. In programming languages, a lambda expression allows you to use a function with executable statements as a parameter, variable or field.
Program that uses lambda expressions [C#]

using System;

class Program
{
    static void Main()
    {
 //
 // Use implicitly typed lambda expression.
 // ... Assign it to a Func instance.
 //
 Func<int, int> func1 = x => x + 1;
 //
 // Use lambda expression with statement body.
 //
 Func<int, int> func2 = x => { return x + 1; };
 //
 // Use formal parameters with expression body.
 //
 Func<int, int> func3 = (int x) => x + 1;
 //
 // Use parameters with a statement body.
 //
 Func<int, int> func4 = (int x) => { return x + 1; };
 //
 // Use multiple parameters.
 //
 Func<int, int, int> func5 = (x, y) => x * y;
 //
 // Use no parameters in a lambda expression.
 //
 Action func6 = () => Console.WriteLine();
 //
 // Use delegate method expression.
 //
 Func<int, int> func7 = delegate(int x) { return x + 1; };
 //
 // Use delegate expression with no parameter list.
 //
 Func<int> func8 = delegate { return 1 + 1; };
 //
 // Invoke each of the lambda expressions and delegates we created.
 // ... The methods above are executed.
 //
 Console.WriteLine(func1.Invoke(1));
 Console.WriteLine(func2.Invoke(1));
 Console.WriteLine(func3.Invoke(1));
 Console.WriteLine(func4.Invoke(1));
 Console.WriteLine(func5.Invoke(2, 2));
 func6.Invoke();
 Console.WriteLine(func7.Invoke(1));
 Console.WriteLine(func8.Invoke());
    }
}

Output

2
2
2
2
4

2
2
Syntax. In many of the statements in the example, you will see the => syntax, which can be read as "goes to" and it separates the arguments from the method body of a lambda expression. It is not a comparison operator. The => syntax can separate an empty parameter list, a formal parameter list or an implicit parameter list from the the body. The right side of the lambda expression can be a statement list inside curly brackets with a return statement, or an expression.
The C# programming languageOverview. The instances with identifiers func1 through func8 all denote anonymous function instances in the C# language. The Func<TResult> type indicates an anonymous function with one result value and no parameter. The Func<T, TResult> type indicates a function with one parameter and one result value. The Action type indicates a function instance that does not receive a parameter and does not return a value.
Delegate keyword. The program also demonstrates how the delegate keyword can be used to denote an anonymous function in the C# language. After the delegate keyword, you can use a formal parameter list or even omit the list if there are no parameters. Afterwards, you must specify a statement list that is executed when the anonymous function is invoked.
Invoking Func and Action instances. Finally, the program demonstrates how you can call the methods that were all specified inside the method body. The Func generic type and the Action type have an instance method called Invoke. It receives a number of parameters that depends on the type. The method body of each of the lambdas and anonymous functions is then executed.

Anonymous functions

The term anonymous function describes both delegates and lambda syntaxes in the C# language. The key part of an anonymous function is that it does not have a name and cannot be invoked with normal method lookup. For this reason, method overloading is not possible for anonymous functions.
Many experts regard lambda expressions as a complete improvement over the delegate syntax. It is sometimes advised that you use lambda expressions instead of the delegate keyword syntax when it is possible.

Specification

The C# language specification itself describes the anonymous function types in the language. The annotated edition of The C# Programming Language (3rd Edition) covers all the syntaxes available, and this article derives its example from the specification's. You can find more detail on this topic using the precise technical terminology on page 314 of this book.

Summary

We looked at the syntactic rules of lambda expressions in the C# programming language with help from the C# specification itself. We described lambda expressions with zero arguments, one argument, two arguments, and one return value. We also looked at the delegate keyword when used for anonymous functions. Finally, we explored the Func generic type in the base class library as well as the Action type, and the Invoke instance methods on these types.

Total Pageviews