Вы находитесь на странице: 1из 18

Predefine delegate in c#

-------------------------

Action, Func and Predicate - Predefined Generic Delegates

Action, Func and Predicate are pre-defined Generic delegates. So as delegate they can point to
functions with specified signature.

Action<>

Does not return any value, and can take from none up to 16 generic parameters. So there are total
of 17 overloads for Action delegate, from no

parameter to up to 16 generic parameters. As it does not return any value, so conventionally named
as Action.

- Action

- Action<T>

- Action<T1, T2>

- Action<T1, T2, T3>

- Action< ……

static void Shout(string arg1, string arg2)

Console.WriteLine(string.Format("{0} {1}!", arg1, arg2));

static void Main(string[] args)

//Create an Action

Action<string, string> action = new Action<string,string>( Shout );

//OR You can initialize it as

Action<string, string> moreAction = Shout;


//Invoke method.

moreAction("Hello", "World");

//will output 'Hello World!'

Actual delegate definition of Action<T1, T2> would be:

public delegate void Action<T1, T2>(T1 param1, T2 param2);

Func<>

Return a generic parameter, and has 17 overloads to support from none up to 16 generic
parameters. Last parameter is the Return type, and is

required. As it does return a parameter, so conventionally named as Func derived from Function.

- Func<TResult>

- Func<T1, TResult>

- Func<T1, T2, TResult>

- Func<T1, T2, T3, TResult>

- Func< ……

Actual delegate definition of Func<T1, T2, out TResult> with two parameters would be:

public delegate TResult Func<T1, T2, out TResult>(T1 param1, T2 param2);

Predicate<>

As name indicate, this delegate defines a method with return type bool, and exactly one generic
parameter. Method is pretty much used as a function

to affirm or deny certain input for specific operation. i.e Either provided input is true or false based
on specific method implementation. Mostly

used as a filter method for given data.


For example, FindAll method for List<T> takes Predicate<T> method as parameter. FindAll method
use provided method against Predicate<T> to apply and

filter against each value of the collection based on Predicate response.

static bool IsEvenNumber(int num)

return num % 2 == 0;

static void Main(string[] args)

//Predicate

Predicate<int> isEvenPredicate = IsEvenNumber;

List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

List<int> evenNumbers = numbers.FindAll(isEvenPredicate);

// output will be 2,4,6,8

Actual delegate definition for Predicate would be:

public delegate bool Predicate<T>(T input);

What are the advantages of pre-defined delegates?

To save time from defining a delegates of similar definition yourself. Use the predefined one which
is also more commonly used, and well recognized.

With the invent of Extension methods and LINQ which introduced loads of functions with the
requirement of delegate parameter. A presence for general

globally defined pre-defined delegates was required.


Ienumerable, enumerator, Iqueryable

-----------------------------------

The IEnumerable interface contains an abstract member function called GetEnumerator() and return
an interface IEnumerator on any success call. This

IEnumerator interface will allow us to iterate through any custom collection.

IEnumerator has two methods MoveNext and Reset. It also has a property called Current.

IEnumerable

IEnumerable exists in the System.Collections namespace.

IEnumerable is suitable for querying data from in-memory collections like List, Array and so on.

While querying data from the database, IEnumerable executes "select query" on the server-side,
loads data in-memory on the client-side and then

filters the data.

IEnumerable is beneficial for LINQ to Object and LINQ to XML queries.

MyDataContext dc = new MyDataContext ();

IEnumerable<Employee> list = dc.Employees.Where(p => p.Name.StartsWith("S"));

list = list.Take<Employee>(10);

IQueryable

IQueryable exists in the System.Linq Namespace.

IQueryable is suitable for querying data from out-memory (like remote database, service)
collections.

While querying data from a database, IQueryable executes a "select query" on server-side with all
filters.

IQueryable is beneficial for LINQ to SQL queries.

MyDataContext dc = new MyDataContext ();

IQueryable<Employee> list = dc.Employees.Where(p => p.Name.StartsWith("S"));

list = list.Take<Employee>(10);
Benefits of using Interfaces

----------------------------

You may feel that it is a waste of time to create interfaces but here is why it is important.

Decoupling, reducing dependency from implementation classes;

Readability, as an interface implements the signature of your code their name must make sense with
their purpose;

Maintainability, making it possible of having different implementations based on the same interface;

Extensibility, being easier to extend classes with a different implementation based on the same
contract.

C# Extension Method

--------------------

An extension method is a static method of a static class, where the "this" modifier is applied to the
first parameter. The type of the first

parameter will be the type that is extended.

Extension methods are only in scope when you explicitly import the namespace into your source
code with a using directive.

Benefits of extension methods

Extension methods allow existing classes to be extended without relying on inheritance or having to
change the class's source code.

If the class is sealed than there in no concept of extending its functionality. For this a new concept is
introduced, in other words extension

methods.

This feature is important for all developers, especially if you would like to use the dynamism of the
C# enhancements in your class's design.
Important points for the use of extension methods

An extension method must be defined in a top-level static class.

An extension method with the same name and signature as an instance method will not be called.

Extension methods cannot be used to override existing methods.

The concept of extension methods cannot be applied to fields, properties or events.

Overuse of extension methods is not a good style of programming.

Define an Extension Method

namespace ExtensionMethods

public static class IntExtensions

public static bool IsGreaterThan(this int i, int value)

return i > value;

Extension method

using ExtensionMethods;

class Program

static void Main(string[] args)

int i = 10;

bool result = i.IsGreaterThan(100);

Console.WriteLine(result);
}

Anonymous Method in C#

-----------------------

An anonymous method is a method which doesn’t contain any name which is introduced in C# 2.0. It
is useful when the user wants to create an inline

method and also wants to pass parameter in the anonymous method like other methods. An
Anonymous method is defined using the delegate keyword and the

user can assign this method to a variable of the delegate type.

using System;

Anonymous methods provide a technique to pass a code block as a delegate parameter. Anonymous
methods are the methods without a name, just the body.

class GFG {

public delegate void petanim(string pet);

// Main method

static public void Main()

// An anonymous method with one parameter

petanim p = delegate(string mypet)

Console.WriteLine("My favorite pet is: {0}",

mypet);

};

p("Dog");

}
}

lambda expression

-----------------

A lambda expression is an anonymous function and it is mostly used to create delegates in LINQ.
Simply put, it's a method without a declaration,

i.e., access modifier, return value declaration, and name.

Func<int, int> multiplyByFive = num => num * 5;

// Returns 35

int result = multiplyByFive(7);

Func<int, int, int> multiplyTwoNumbers = (a, b) => a * b;

// Returns 35

int result = multiplyTwoNumbers(7, 5);

Difference between Ref and Out keywords in C#

---------------------------------------------

The out is a keyword in C# which is used for the passing the arguments to methods as a reference
type. It is generally used when a method returns

multiple values. The out parameter does not pass the property.

The ref is a keyword in C# which is used for the passing the arguments by a reference. Or we can say
that if any changes made in this argument in the

method will reflect in that variable when the control return to the calling method. The ref parameter
does not pass the property.

difference between a static and non-static class -

------------------------------------------------------
Non-static classes can be instantiated, whereas static classes cannot be instantiated i.e. you cannot
use the new keyword to create a variable of the

class type

Static classes can only have static methods.

Non-static classes can have instance method and static methods.

ou access the members of a static class by using the class name itself

Static class is sealed.

Different B/W Private constructor of a class and Singletone class

----------------------------------------------------------------------

A private constructor is used in classes containing only static member as shown below −

class Demo {

// private constructor

private Demo() { }

public static a = 10;

A singleton class has normal methods and you can call it using an instance.

To prevent multiple instances of the class, the private constructor is used.

Let us see an example −

public class Singleton {


static Singleton a = null;

private Singleton() {

Different B/W Seald class and Private class

-------------------------------------------

Private: Private limits the visiblity to a scope. Declaring a private class within a class means that "sub-
class" can't be seen from outside of the

class.

This is also true for methods and properties - they can be seen within the class, but not to any
consumers or inheritors.

Private keyword is used for declaring class.

Sealed: If a class is declared as sealed, that means that you cannot inherit from the class. Sealed class
can be used when a class is internal to the

operation of the library, class or whwn you donot want that class to be overridden because it may
affect the functionality.

Sealed keyword is used for declaring class

Virtual vs Sealed vs New vs Abstract in C#

------------------------------------------

Virtual

The virtual keyword allows a class to be overridden. For overriding a parent class method in the child
class, declare the parent class method as

virtual.

Sealed

When a class is declared sealed, it cannot be inherited, abstract classes cannot be declared sealed.
To prevent being overridden, use the sealed in C#. When you use sealed modifiers in C# on a
method, then the method loses its capabilities of

overriding. The sealed method should be part of a derived class and the method must be an
overridden method.

public sealed override void getResult() { }

New

Use the new keyword to hide the base class method from the derived class. This is done by declaring
the derived class function with new. This is how

new is used in Shadowing.

public new string getResult()

Abstract

Abstract classes contain abstract methods, which are implemented by the derived class.

abstract class Vehicle

What is a bubbled event?

------------------------

Handling child controls events through parent control in data bind controls known as event bubbling.
That means, when events occurred in child

controls , the event is bubbled to the parent control. A control can participate in event bubbling
through two methods that it inherits from the base

class System.Web.UI.Control. These methods are OnBubbleEvent and RaiseBubbleEvent. To handle


or to raise the bubbled event, a control must override

the OnBubbleEvent method. RaiseBubbleEvent sends the event data up the hierarchy to the
control's parent.
Event Bubbling is nothing but events raised by child controls is handled by the parent control.
Example: Suppose consider grid view as parent control

in which there are several child controls.There can be a column of link buttons right.Each link button
has click event.Instead of writing event

routine for each link button write one routine for parent which will handle the click events of the
child link button events.

Delegate and Events

-------------------

Events:

Event is a mechanism by which a class can send notification to its client. For example, you have an
application to perform certain operation, if an

operation is failed then the application send the notification to log file, printer, fax, email etc.

Events are declared using delegates. Without delegate, we can not create Events.

Delegate:

A delegate in C# is similar to a function pointer in C. A delegate object holds the reference of one or
more methods. Delegate creation is the four

steps process.

Declaration of delegate

Delegate object creation

Point the reference to the method.

Invoke delegate
A delegate object doesn't care about the class in which the function exists. There is only one
restriction that the delegate signature and the

function signature should be same otherwise delegate object can’t hold the reference of the method
which doesn't have the same signature. Signature

means return type and parameters.

namespace SampleApp {

public delegate string MyDel(string str);

class EventProgram {

event MyDel MyEvent;

public EventProgram() {

this.MyEvent += new MyDel(this.WelcomeUser);

public string WelcomeUser(string username) {

return "Welcome " + username;

static void Main(string[] args) {

EventProgram obj1 = new EventProgram();

string result = obj1.MyEvent("Tutorials Point");

Console.WriteLine(result);

Virtual function and Function over loading

---------------------------------------------

The function which you want to do overload must be a virtual function. Otherwise, it will not
overload and overwrite.
Exception handling

------------------

C# Exception handling is a mechanism in .NET to detect and handle run time errors. The try..catch
block is used to implement exception handling in

C#. In try..catch..finally block, finally is used for code cleanup. Code sample for multiple try catch
block.

try..catch..finally

C# provides three keywords try, catch and finally to implement exception handling. The try encloses
the statements that might throw an exception

whereas catch handles an exception if one exists. The finally can be used for any cleanup work that
needs to be done.

Try..catch..finally block example:

try

// Statement which can cause an exception.

catch(Type x)

// Statements for handling the exception

finally

//Any cleanup code

Throwing an Exception
In C#, it is possible to throw an exception programmatically. The 'throw' keyword is used for this
purpose. The general form of throwing an exception

is as follows.

throw exception_obj;

For example, the following statement throws an ArgumentException explicitly.

throw new ArgumentException("Exception");

//C#: Exception Handling:

using System;

class MyClient

public static void Main()

try

throw new DivideByZeroException("Invalid Division");

catch (DivideByZeroException)

Console.WriteLine("Exception");

Console.WriteLine("LAST STATEMENT");

Re-throwing an Exception

The exceptions, which we caught inside a catch block, can re-throw to a higher context by using the
keyword throw inside the catch block. The

following program shows how to do this.

//C#: Exception Handling: Handling all exceptions


using System;

class MyClass

public void Method()

try

int x = 0;

int sum = 100 / x;

catch (DivideByZeroException)

throw;

class MyClient

public static void Main()

MyClass mc = new MyClass();

try

mc.Method();

catch (Exception)

Console.WriteLine("Exception caught here");

Console.WriteLine("LAST STATEMENT");

}
}

Standard Exceptions

System.OutOfMemoryException

System.NullReferenceException

Syste.InvalidCastException

Syste.ArrayTypeMismatchException

System.IndexOutOfRangeException

System.ArithmeticException

System.DevideByZeroException

System.OverFlowException

User-defined Exceptions

In C#, it is possible to create our own exception class. But Exception must be the ultimate base class
for all exceptions in C#. So the user-defined

exception classes must inherit from either Exception class or one of its standard derived classes.

//C#: Exception Handling: User defined exceptions

using System;

class MyException : Exception

public MyException(string str)

Console.WriteLine("User defined exception");

class MyClient

public static void Main()

{
try

throw new MyException("RAJESH");

catch (Exception)

Console.WriteLine("Exception caught here" + e.ToString());

Console.WriteLine("LAST STATEMENT");

Final, Finally and Finallize

----------------------------

final – constant declaration.

finally – The finally block always executes when the try block exits, except System.exit(0) call. This
ensures that the finally block is executed

even if an unexpected exception occurs.

finalize() – method helps in garbage collection. A method that is invoked before an object is
discarded by the garbage collector, allowing it to

clean up its state.

Вам также может понравиться