0% found this document useful (0 votes)
115 views

Introduction To C#

C# is a modern and powerful object-oriented programming language created by Microsoft. It was created by Anders Hejlsberg and team to take the best aspects of existing languages like C++ and Java and improve upon them. C# aims to be simple, modern, and flexible. It supports features like generics, delegates, and lambda expressions. C# can be used to create many types of applications from web sites to compilers.

Uploaded by

suresh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
115 views

Introduction To C#

C# is a modern and powerful object-oriented programming language created by Microsoft. It was created by Anders Hejlsberg and team to take the best aspects of existing languages like C++ and Java and improve upon them. C# aims to be simple, modern, and flexible. It supports features like generics, delegates, and lambda expressions. C# can be used to create many types of applications from web sites to compilers.

Uploaded by

suresh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 24

Introduction to c#

C# Released to the public in June 2000.

C# is a new language created by Microsoft and submitted to the ECMA for standardization. This
new language was created by a team of people at Microsoft led by Anders Hejlsberg .

Hejlsberg is a Microsoft Distinguished Engineer who has created other products and languages,
including Borland Turbo C++ and Borland Delphi. With C#, they focused on taking what was
right about existing languages and adding improvements to make something better.

C# is a powerful and flexible programming language. Like all programming languages, it can be
used to create a variety of applications.

The language does not place constraints on what you can do. C# has already been used for
projects as diverse as dynamic Web sites, development tools, and even compilers.

C# syntax simplifies many of the complexities of C++ and provides powerful features such as
nullable value types, enumerations, delegates, lambda expressions and direct memory access,
which are not found in Java.

C# supports generic methods and types, which provide increased type safety and performance,
and iterators, which enable implementers of collection classes to define custom iteration
behaviors that are simple to use by client code.

 These objectives about C#:

 C# is simple.
 C# is modern.
 C# is object-oriented.

In addition to Microsoft's reasons, there are other reasons to use C#:

 C# is powerful and flexible.


 C# is a language of few words.
 C# is modular.
 C# will be popular.

C# Is Simple
 C# removes some of the complexities and pitfalls of languages such as Java and C++,
including the removal of macros, templates, multiple inheritance, and virtual base classes.
These are all areas that cause either confusion or potential problems for C++ developers.
C# is simple because it is based on C and C++. If you are familiar with C and C++, or
even Java, you will find C# very familiar in many aspects. Statements, expressions,
operators, and other functions are taken directly from C and C++, but improvements
make the language simpler.

Some of the improvements include eliminating redundancies. Other areas of


improvement include additional syntax changes. For example, C++ has three operators
for working with members: ::, ., and ->. Knowing when to use each of these three
symbols can be very confusing in C++.
In C#, these are all replaced with a single symbol the "dot" operator. For newer
programmers, this and many other features eliminate a lot of confusion.

C# is modern
 Features such as exception handling, garbage collection, extensible data types, and code
security are features that are expected in a modern language. C# contains all of these.y
other features eliminate a lot of confusion.

C# Is Powerful and Flexible


The language places no constraints on what can be done. C# can be used for projects as diverse
as creating word processors, graphics, spreadsheets, and even compilers for other languages.

C# Is a Language of Few Words


C# is a language that uses a limited number of words. C# contains only a handful of terms,
called keywords, which serve as the base on which the language's functionality is built.

C# Is Modular
C# code can (and should) be written in chunks called classes, which contain routines
called member methods. These classes and methods can be reused in other applications or
programs. By passing pieces of information to the classes and methods, you can create useful,
reusable code.

C# Will Be Popular
C# is one of the newest programming languages. One of the key reasons is Microsoft and the
promises of .NET.

NULLABLE

By default value types are non nullable. To make them nullable use ?
int i = 0 (i is non nullable, so "i" cannot be set to null, i = null will generate compiler error)
int? j = 0 (j is nullable int, so j=null is legal)

Nullable types bridge the differences between C# types and Database types
Program without using NULL coalescing operator
using System;
class Program
{
    static void Main()
  {
        int AvailableTickets;
        int? TicketsOnSale = null;

        if (TicketsOnSale == null)
    {
            AvailableTickets = 0;
    }
        else
    {
            AvailableTickets = (int)TicketsOnSale;
    }

        Console.WriteLine("Available Tickets={0}", AvailableTickets);


  }
}

The above program is re-written using NULL coalescing operator


using System;
class Program
{
    static void Main()
  {
        int AvailableTickets;
        int? TicketsOnSale = null;

        //Using null coalesce operator ??


        AvailableTickets = TicketsOnSale ?? 0;

        Console.WriteLine("Available Tickets={0}", AvailableTickets);


  }

DELEGATE

A delegate is a type safe function pointer.That is, they hold reference(Pointer) to a function. 

The signature of the delegate must match the signature of the function, the delegate points to,
otherwise you get a compiler error. This is the reason delegates are called as type safe function
pointers.

A Delegate is similar to a class. You can create an instance of it, and when you do so, you pass
in the function name as a parameter to the delegate constructor, and it is to this function the
delegate will point to.

Tip to remember delegate syntax: Delegates syntax look very much similar to a method with
a delegate keyword.

Sample Delegate Program:

using System;

// Delegate Declaration. 
public delegate void HelloFunctionDelegate(string Message);

class Pragim
{
    public static void Main()
  {
        // Create the instance of the delegate and pass in the function
        // name as the parameter to the constructor. The passed in
        // function signature must match the signature of the delegate
        HelloFunctionDelegate del = new HelloFunctionDelegate(Hello);
        // Invoke the delegate, which will invoke the method
        del("Hello from Delegte");
  }

    public static void Hello(string strMessge)


  {
        Console.WriteLine(strMessge);
  }
}

Example2:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

class Delegate
{
public static void Main()
{
List<Employee> emplist = new List<Employee>();
emplist.Add(new Employee() { ID = 101, Name = "Mohan", Salary = 5000, Experience = 5 });
emplist.Add(new Employee() { ID = 102, Name = "Alan", Salary = 6000, Experience = 6 });
emplist.Add(new Employee() { ID = 103, Name = "Suresh", Salary = 7000, Experience = 3 });
emplist.Add(new Employee() { ID = 104, Name = "Jay", Salary = 4000, Experience = 3 });
emplist.Add(new Employee() { ID = 105, Name = "Sachin", Salary = 4500, Experience = 3 });
IsPromotable del = new IsPromotable(Promote);
Employee.PromoteEmployee(emplist,del);
Console.ReadLine();
}
public static bool Promote(Employee emp)
{
if(emp.Experience >=5)
{
return true;
}
else
{
return false;
}
}

}
delegate bool IsPromotable(Employee emp);

class Employee
{
public int ID { get; set; }
public string Name { get; set; }
public int Salary { get; set; }
public int Experience { get; set; }

public static void PromoteEmployee(List <Employee> emplist, IsPromotable ispromotable)


{
foreach (Employee employee in emplist)
{
if (ispromotable(employee))
{
Console.WriteLine(employee.Name + " is promoted");
}
}
}
}

Multicast delegate:

A Multicast delegate is a delegate that has references to more than one function. When
you invoke a multicast delegate, all the functions the delegate is pointing to, are invoked.

There are 2 approaches to create a multicast delegate.

Approach 1: 
using System;
namespace Sample
{
    public delegate void SampleDelegate();
    
    public class Sample
  {
        static void Main()
    {
            SampleDelegate del1 = new SampleDelegate(SampleMethodOne);
            SampleDelegate del2 = new SampleDelegate(SampleMethodTwo);
            SampleDelegate del3 = new SampleDelegate(SampleMethodThree);
            // In this example del4 is a multicast delegate. You use +(plus) 
            // operator to chain delegates together and -(minus) operator to remove.
            SampleDelegate del4 = del1 + del2 + del3 - del2;
            
            del4();
    }

        public static void SampleMethodOne()


    {
            Console.WriteLine("SampleMethodOne Invoked");
    }

        public static void SampleMethodTwo()


    {
            Console.WriteLine("SampleMethodTwo Invoked");
    }

        public static void SampleMethodThree()


    {
            Console.WriteLine("SampleMethodThree Invoked");
    }
  }
}
Approach 2:
using System;
namespace Sample
{
    public delegate void SampleDelegate();
    
    public class Sample
  {
        static void Main()
    {
            // In this example del is a multicast delegate. You use += operator 
            // to chain delegates together and -= operator to remove.
            SampleDelegate del = new SampleDelegate(SampleMethodOne);
            del += SampleMethodTwo;
            del += SampleMethodThree;
            del -= SampleMethodTwo;
            
            del();
    }

        public static void SampleMethodOne()


    {
            Console.WriteLine("SampleMethodOne Invoked");
    }

        public static void SampleMethodTwo()


    {
            Console.WriteLine("SampleMethodTwo Invoked");
    }

        public static void SampleMethodThree()


    {
            Console.WriteLine("SampleMethodThree Invoked");
    }
  }
}

Note: A multicast delegate, invokes the methods in the invocation list, in the same order in
which they are added.

If the delegate has a return type other than void and if the delegate is a multicast
delegate, only the value of the last invoked method will be returned. Along the same
lines, if the delegate has an out parameter, the value of the output parameter, will be the
value assigned by the last method.

Example: Multicast delegate with an int return type


using System;
namespace Sample
{
    // Deletegate's return type is int
    public delegate int SampleDelegate();
    
    public class Sample
  {
        static void Main()
    {
            SampleDelegate del = new SampleDelegate(SampleMethodOne);
            del += SampleMethodTwo;

            // The ValueReturnedByDelegate will be 2, returned by the SampleMethodTwo(),


            // as it is the last method in the invocation list.
            int ValueReturnedByDelegate = del();

            Console.WriteLine("Returned Value = {0}", ValueReturnedByDelegate);


    }

        // This method returns one


        public static int SampleMethodOne()
    {
            return 1;            
    }

        // This method returns two


        public static int SampleMethodTwo()
    {
            return 2;
    }
  }
}

Example: Multicast delegate with an integer output parameter.


using System;
namespace Sample
{
    // Deletegate has an int output parameter
    public delegate void SampleDelegate(out int Integer);
    
    public class Sample
  {
        static void Main()
    {
            SampleDelegate del = new SampleDelegate(SampleMethodOne);
            del += SampleMethodTwo;

            // The ValueFromOutPutParameter will be 2, initialized by SampleMethodTwo(),


            // as it is the last method in the invocation list.
            int ValueFromOutPutParameter = -1;
            del(out ValueFromOutPutParameter);

            Console.WriteLine("Returned Value = {0}", ValueFromOutPutParameter);


    }

        // This method sets ouput parameter Number to 1


        public static void SampleMethodOne(out int Number)
    {
            Number = 1;
    }

        // This method sets ouput parameter Number to 2


        public static void SampleMethodTwo(out int Number)
    {
            Number = 2;
    }
  }
}

Name space :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using projectA.teamA;

namespace namespaceexample
{
class Program
{
static void Main(string[] args)
{
classA.print();
projectA.teamB.classB.print();

}
}
}
namespace projectA
{
namespace teamA
{
class classA
{

public static void print()


{
Console.WriteLine("class A");
}

}
}
}
namespace projectA
{
namespace teamB
{

class classB
{
public static void print()
{
Console.WriteLine("class B");
}
}

}
}

OUTPUT:
CLASSA
CLASSB

EXAMPLE2:
Allias name:

using PATA = projectA.teamA;


using PATB = projectA.teamB;

namespace namespaceexample
{
class Program
{
static void Main(string[] args)
{
PATA.classA.print();
PATB.classB.print();

}
}
}

Get set accessor

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication2
{
public class Program

{
public static int NumberOfEmployees;
private static int counter;
private string name;

// A read-write instance property:


public string Name
{
get { return name; }
set { name = value; }
}

// A read-only static property:


public static int Counter
{
get { return counter; }
}

// A Constructor:
public Program()
{
// Calculate the employee's number:
counter = ++counter + NumberOfEmployees;
}
}

class TestEmployee
{
static void Main()
{
Program.NumberOfEmployees = 107;
Program e1 = new Program();
e1.Name = "Claude Vige";

System.Console.WriteLine("Employee number: {0}", Program.Counter);


System.Console.WriteLine("Employee name: {0}", e1.Name);
Console.ReadLine();
}
}

Auto implemented property

using System;

public class SaleItem


{
public string Name
{ get; set; }

public decimal Price

{ get; set; }
}

class Program
{
static void Main(string[] args)
{
var item = new SaleItem{ Name = "Shoes", Price = 19.95m };
Console.WriteLine($"{item.Name}: sells for {item.Price:C2}");
}
}
Data types

Variables are simply places to store data like numbers, strings (text), arrays of numbers or
strings, and other objects. Each variable can only store data of one type, and you
must declare variables before attempting to set or get their values.
The variables in C#, are categorized into the following types −

 Value types
 Reference types
 Pointer types
Value Type
Value type variables can be assigned a value directly. They are derived from the
class System.ValueType.

The value types directly contain data. Some examples are int, char, and float, which stores
numbers, alphabets, and floating point numbers, respectively. When you declare an int type, the
system allocates memory to store the value.

Type Represents Range Default


Value

bool Boolean value True or False False

byte 8-bit unsigned integer 0 to 255 0

char 16-bit Unicode character U +0000 to U +ffff '\0'

decimal 128-bit precise decimal 0.0M


values with 28-29 (-7.9 x 1028 to 7.9 x 1028) / 100to 28
significant digits

double 64-bit double-precision (+/-)5.0 x 10-324 to (+/-)1.7 x 10308 0.0D


floating point type

float 32-bit single-precision 0.0F


-3.4 x 1038 to + 3.4 x 1038
floating point type

int 32-bit signed integer type -2,147,483,648 to 2,147,483,647 0


long 64-bit signed integer type -9,223,372,036,854,775,808 to 0L
9,223,372,036,854,775,807

sbyte 8-bit signed integer type -128 to 127 0

short 16-bit signed integer type -32,768 to 32,767 0

uint 32-bit unsigned integer type 0 to 4,294,967,295 0

ulong 64-bit unsigned integer type 0 to 18,446,744,073,709,551,615 0

ushort 16-bit unsigned integer type 0 to 65,535 0

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace datatypeexample
{

class Program
{
static void Main(string[] args)
{
Console.WriteLine("Size of int: {0}", sizeof(int));

Console.WriteLine("Size of boolean: {0}", sizeof(bool));

Console.WriteLine("Size of byte: {0}", sizeof(byte));

Console.WriteLine("Size of char: {0}", sizeof(char));

Console.WriteLine("Size of float: {0}", sizeof(float));

Console.WriteLine("Size of decimal: {0}", sizeof(decimal));

Console.WriteLine("Size of double: {0}", sizeof(double));

Console.WriteLine("Size of sbyte: {0}", sizeof(sbyte));

Console.WriteLine("Size of ulong: {0}", sizeof(ulong));

Console.WriteLine("Size of short: {0}", sizeof(short));

Console.WriteLine("Size of uint: {0}", sizeof(uint));


Console.WriteLine("Size of ushort: {0}", sizeof(ushort));
String str = @"Tutorials Point";

Console.WriteLine("string is: {0}",str);


String str1 = "Tutorials Point";

Console.WriteLine("string is: {0}", str1);


dynamic data = 12;
float a = 10;

Console.WriteLine("add value is: {0}", a+data);

Console.ReadLine();
}
}
}

Reference Type
The reference types do not contain the actual data stored in a variable, but they contain a
reference to the variables.

In other words, they refer to a memory location. Using multiple variables, the reference types
can refer to a memory location. If the data in the memory location is changed by one of the
variables, the other variable automatically reflects this change in value. Example of built-
in reference types are: object, dynamic, and string.

object obj;

obj = 100; // this is boxing

Example:

class ObjectTest
{
public int i = 10;
}

class MainClass2
{
static void Main()
{
object a;
a = 1; // an example of boxing
Console.WriteLine(a);
Console.WriteLine(a.GetType());
Console.WriteLine(a.ToString());
a = new ObjectTest();
ObjectTest classRef;
classRef = (ObjectTest)a;
Console.WriteLine(classRef.i);
}
}

Dynamic Type
You can store any type of value in the dynamic data type variable. Type checking for these
types of variables takes place at run-time.

Syntax for declaring a dynamic type is −

dynamic <variable_name> = value;


For example,

dynamic d = 20;

Dynamic types are similar to object types except that type checking for object type variables
takes place at compile time, whereas that for the dynamic type variables takes place at run time.

String Type
The String Type allows you to assign any string values to a variable. The string type is an alias
for the System.String class. It is derived from object type. The value for a string type can be
assigned using string literals in two forms: quoted and @quoted.

For example,

String str = "Tutorials Point";

A @quoted string literal looks as follows −

@"Tutorials Point";

The user-defined reference types are: class, interface, or delegate. 

Type conversion
Type conversion is converting one type of data to another type. It is also known as Type
Casting. In C#, type casting has two forms −

 Implicit type conversion − These conversions are performed by C# in a type-safe


manner. For example, are conversions from smaller to larger integral types and
conversions from derived classes to base classes.
 Explicit type conversion − These conversions are done explicitly by users using the pre-
defined functions. Explicit conversions require a cast operator.

The following example shows an explicit type conversion 


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace datatypeexample
{

class Program
{

static void Main(string[] args) {


double d = 5673.74;
int i1;
int i;
float a=10f;

// cast double to int.


i = (int)d;
Console.WriteLine(i1);

// cast float to int not possible.


i = (float)a;
Console.WriteLine(i);
Console.ReadKey();
}
}
}

Constant

Constants are immutable values which are known at compile time and do not change
for the life of the program. Constants are declared with the const modifier. 

C# does not support const methods, properties, or events.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace constantexample
{
static class Constants
{
public const double Pi = 3.14159;
public const int SpeedOfLight = 300000; // km per sec.

}
class Program
{
static void Main()
{
double radius = 5.3;

double area = Constants.Pi * (radius * radius);


int secsFromSun = 149476000 / Constants.SpeedOfLight; // in km
Console.WriteLine(secsFromSun);
Console.ReadLine();
}
}

Example2
the Constants are of two types

1. Compile time constants (const)


2. Runtime constants  (Readonly)

  Compile time constants 

The compile time constants are declared by using the const keyword which value can not be
changed during the execution of the program.

Syntax
 
     int const a=10;
Some key points about const variable

   Its must to assign value at the time of declaration.

             eg.
             int const a=10;  

   const only allow constant variables into the expression.

   eg.
          int const a=10;
          int const b=20; // correct
          int const c=a+b; 
 
          int  d=1;
          int const c=d+b;   //compile time error because d variable is the non constant into
expression.
 

   const can be declared at class level as well as inside the method.


  const can not be declared using static keyword because they are by default static.
   constants are  absolute constant which value can`t be changed or assigned at the run
time.
 constant variable are compile time constant variable.

Runtime constants (Readonly)

The Run time constants are declared by using the Readonly keyword which value can not be
changed during the execution of the program.

Syntax
int Readonly a; or
 int Readonly a=0;
Some key points about const variable

  Its not  must to assign value at the time of declaration,we can also assign the value for
readonly through constructor.

eg.
int readonly a;
a=0;

   Readonly allows, readonly  constant as wel as non  readonly constant  variables into the
expression.

eg.
int readonly a=10;
int b=1;
int readonly c=a+b;

 Readonly can be declared only at class level not inside the method.
 Readonly can not be declared using static keyword because they are by default static.
 Readonly   constants  value can  be set through reference variable.
 Readonly  constant variable are runtime time constant variable.
DATE TIME FORMAT

using System;

class Program
{
static void Main()
{
DateTime time =
DateTime.Now; // Use
current time.
string format = "MMM ddd
d HH:mm yyyy"; // Use this
format.

Console.WriteLine(time.ToString(
format)); // Write to console.
}
}

Output

Feb Tue 21 13:15 2017

Format string pattern

MMM display three-letter


month
ddd display three-letter day
of the WEEK
d display day of the MONTH
HH display two-digit hours
on 24-hour scale
mm display two-digit
minutes
yyyy display four-digit year

NUMBER FORMAT

double value;

value = 123;
Console.WriteLine(value.ToString("00000"));
Console.WriteLine(String.Format("{0:00000}", value));
// Displays 00123

value = 1.2;
Console.WriteLine(value.ToString("0.00", CultureInfo.InvariantCulture));
Console.WriteLine(String.Format(CultureInfo.InvariantCulture,
"{0:0.00}", value));
// Displays 1.20

Console.WriteLine(value.ToString("00.00", CultureInfo.InvariantCulture));
Console.WriteLine(String.Format(CultureInfo.InvariantCulture,
"{0:00.00}", value));
// Displays 01.20

CultureInfo daDK = CultureInfo.CreateSpecificCulture("da-DK");


Console.WriteLine(value.ToString("00.00", daDK));
Console.WriteLine(String.Format(daDK, "{0:00.00}", value));
// Displays 01,20

value = .56;
Console.WriteLine(value.ToString("0.0", CultureInfo.InvariantCulture));
Console.WriteLine(String.Format(CultureInfo.InvariantCulture,
"{0:0.0}", value));
// Displays 0.6

value = 1234567890;
Console.WriteLine(value.ToString("0,0", CultureInfo.InvariantCulture));
Console.WriteLine(String.Format(CultureInfo.InvariantCulture,
"{0:0,0}", value));
// Displays 1,234,567,890

CultureInfo elGR = CultureInfo.CreateSpecificCulture("el-GR");


Console.WriteLine(value.ToString("0,0", elGR));
Console.WriteLine(String.Format(elGR, "{0:0,0}", value));
// Displays 1.234.567.890

value = 1234567890.123456;
Console.WriteLine(value.ToString("0,0.0", CultureInfo.InvariantCulture));
Console.WriteLine(String.Format(CultureInfo.InvariantCulture,
"{0:0,0.0}", value));
// Displays 1,234,567,890.1

value = 1234.567890;
Console.WriteLine(value.ToString("0,0.00", CultureInfo.InvariantCulture));
Console.WriteLine(String.Format(CultureInfo.InvariantCulture,
"{0:0,0.00}", value));
// Displays 1,234.57

# CUSTOM PLACEHOLDER
double value;

value = 1.2;
Console.WriteLine(value.ToString("#.##", CultureInfo.InvariantCulture));
Console.WriteLine(String.Format(CultureInfo.InvariantCulture,
"{0:#.##}", value));
// Displays 1.2

value = 123;
Console.WriteLine(value.ToString("#####"));
Console.WriteLine(String.Format("{0:#####}", value));
// Displays 123

value = 123456;
Console.WriteLine(value.ToString("[##-##-##]"));
Console.WriteLine(String.Format("{0:[##-##-##]}", value));
// Displays [12-34-56]

value = 1234567890;
Console.WriteLine(value.ToString("#"));
Console.WriteLine(String.Format("{0:#}", value));
// Displays 1234567890

Console.WriteLine(value.ToString("(###) ###-####"));
Console.WriteLine(String.Format("{0:(###) ###-####}", value));
// Displays (123) 456-7890

DELEGATES EXAMPLE

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace anonymoueexample
{
class Program
{
delegate int delegatetpointtoadd(int num1,int num2);
static void Main(string[] args)
{
delegatetpointtoadd s = new delegatetpointtoadd(add);
Console.WriteLine(s.Invoke(2,6).ToString());
Console.ReadLine();
}
static int add(int num1, int num2)
{
return num1 + num2;
}
}
}
Anonymous example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace anonymoueexample
{
class Program
{
delegate int delegatetpointtoadd(int num1,int num2);
static void Main(string[] args)
{
delegatetpointtoadd s = delegate(int num1, int num2)
{
return num1 + num2;
};

Console.WriteLine(s.Invoke(2,6).ToString());
Console.ReadLine();
}
// static int add(int num1, int num2)
//{
// return num1 + num2;
// }
}
}

ANANYMOUS CONVERSION:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace anonymstolamda
{
class Program
{
static void Main(string[] args)
{
List<string> names = new List<string>();
names.Add("suresh");
names.Add("uma");
names.Add("umalakshmi");
string result = names.Find(searchname);
if (result == null)
Console.WriteLine("name not found");
else
Console.WriteLine("name found ");
}

public static bool searchname(string name)


{
return name.Equals("suresh");

}
}

Converted to anonymous function:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace anonymstolamda
{
class Program
{
static void Main(string[] args)
{
List<string> names = new List<string>();
names.Add("suresh");
names.Add("uma");
names.Add("umalakshmi");
string result = names.Find(delegate(string name)
{
return name.Equals("suresh");
}

);
if (result == null)
Console.WriteLine("name not found");
else
Console.WriteLine("name found ");
}

}
}

Converted into lamda expression

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace anonymstolamda
{
class Program
{
static void Main(string[] args)
{
List<string> names = new List<string>();
names.Add("suresh");
names.Add("uma");
names.Add("umalakshmi");
string result = names.Find(name=>name.Equals("suresh1"));

if (result == null)
Console.WriteLine("name not found.....");
else
Console.WriteLine("name found ");
}

}
}

You might also like