A Developer Journey who codes for fun

Daily Dose Of Code

  • Home
  • Dot.Net Basics
    • .Net Basics
      • CTS
      • CLS
      • CLR
      • Strong Vs Weak Ref
      • .Net Framework
      • What is Manifest
    • Memory Management
      • Garbage Collection 1
      • Garbage Collection 2
      • Circular Reference
  • C Sharp
    • Abstract Class in C#
    • Interfaces in C#
    • Value type by Val and By Ref
    • Var keyword
    • Null Coalescing Operator
    • Buit-in code snippets
  • OOPS
    • Abstraction and Encapsulation
    • Polymorphism
    • Inheritence
    • Aggregation
  • Threading
    • Delegates
      • Calling Delegate using Invoke, BeginInvoke
      • Multicast Delegate
      • Exception Handling in Multicast Delegate
      • Action
      • Predicate
      • Func
    • Synchronization
    • Thread Pool
    • Exception Handling
    • TPL
  • Design Pattern
    • Creational Patterns
      • Singleton Pattern
      • Factory Pattern
      • Abstract Factory Pattern
      • Prototype Pattern
      • Builder Pattern
    • Structural Patterns
      • Adapter Pattern
      • Bridge Pattern
      • Composite Pattern
      • Proxy Pattern
      • Facade Pattern
      • Decorator Pattern
      • Flyweight Pattern
    • Behavioral Patterns
      • Command Pattern
      • Interpreter Pattern
      • Iterator Pattern
      • Mediator Pattern
      • Memento Pattern
      • Observer Pattern
      • State Pattern
      • Strategy Pattern
      • Visitor Pattern
      • Chain Of Responsibility Pattern
      • Template Pattern
  • Data Structures
    • Generic List in C#
    • 2d array to 1d array
    • 3d arrayto 1d array
    • Linked List
      • Singly Linked List in C#
    • Queue
      • Dummy Data 1
    • Stack
      • Dummy Data 2
    • Tree
      • Dummy Data 3
    • Graph
      • Dummy Data 4
  • WCF
    • WCF Service using VS 2015
  • Scripts
    • Chrome Extensions
      • Create a Chrome Extension
      • Facebook autologout script
      • Gmail autologout script

Predicate delegate in C#

 Unknown     9:39 AM     C#, Threading     363 comments   

Hello Everyone, In the article we will talk about Predicate delegate.

Predicate is also a delegate which encapsulate a method that takes  only one parameter and returns a bool value - true or false.











So in general Predicate is -

1. Which is contra variant
2. Takes one parameter and return true or false.
Let's talk about some use case of predicates -
1. Let's say we want to filter some data in a collection. We can provide a predicate which will take the input of collection and returns bool value.
e.g. - In WPF when we implement list view filtering. It is very useful
2. Some extension methods also take predicate as a parameter. e.g - List.FindAll(predicate)
Please have a look on implementation of predicate.





















Hope you like reading the article. Please inbox me in case of any confusion.
Happy Coding :)

Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Func Delegate in C#

 Unknown     11:06 AM     C#, Threading     No comments   

Hello Everyone, In this article we will talk about Func< in T, out TResult>  Delegate.
 
It is another readymade delegate that provides by .Net framework. It can encapsulate a method that takes some parameters as input and returns an output as TResult.









So in general Func is a delegate

1. Which takes from 0 to 16 parameters.
2.  It is contra variant and co variant both. Input parameters are contra variant and Output parameters are co variant.
Where can we use Func delegate ?
You can use this delegate to encapsulate a method where you need to pass some parameter( 0 to 16 ) and need to get some result. In this case you do not need to explicitly create a delegate. Func is perfect placeholder.
Let's see a complete example of Func delegate -















Use case - Let's say An array is given and you have to print only odd numbers.

Solution - You can create a foreach loop and check  if the number is odd then print that
At later stage of development you get some more rules added. Let's say print those odd numbers which are greater than 5.
So in this case you have to modify your for loop which can be at the UI level. In that case we will break some SOLID rules.

What is the solution ?
We can create a Func that takes input of array and apply all the rules and return list of data or one by one. This can be at model level and UI won't be aware of the logic and functionality.

Hope you like reading the article. Please inbox me in case of any confusion.
Happy Coding :)

Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Action Delegate in C#

 Unknown     4:41 AM     C#, Threading     No comments   

Hello everyone, in this article we will talk about “Action” a readymade delegate.

Action is just another delegate that takes some parameters and doesn’t return a value. So when do you want to execute some method which doesn’t return any value then rather creating your own delegate. .Net framework provides us an Action Delegate. Please have a look on below image –








So In general Action is a delegate -
  • Which is contra variant ( in parameter  will discuss this in next articles )
  • Which takes 1 to 16 parameters but do not return any value.

So let’s take an example of using Action –

private static void MyActionMethod()
        {
           Action obj = new Action(MyDummyMethod);
           //Synchronous way
           obj.Invoke();
           //Asynchronous way
           obj.BeginInvoke(null, null);
           Console.ReadLine();
           // You can call it as asynchronous way because this is just a delegate
        }

Cool J So we saw in this example we can invoke an action as a synchronous way as well as asynchronous way because Action is none other than a delegate.
Action using Lambda Expressions –

static Action<string> MyActionUsingLambda = str => Console.WriteLine(str);
MyActionUsingLambda("saurabh");

Action using Anonymous Functions-

Action<string> MyActionUsingAnounymous = delegate(string str)
        {
            Console.WriteLine(str);
        };
public void ActionUsingAnonymousMethod(string str)
        {
            MyActionUsingAnounymous(str);
        }

So that was all about Action in C#.

Hope you like reading the article. Please inbox me in case of any confusion you have.
Happy CodingJ


 
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Exception Handling in Multicast Delegate ?

 Unknown     5:25 AM     C#, Threading     No comments   

Hello Guys, In this article we will discuss about how to handle exception in multicast delegate ?

In case you want to understand Delegate and Multicast Delegate. Please visit the links -

Delegate-Delegates
Multicast Delegate-Multicast Delegate

Please look this example -

 
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Multicast Delegate in C#

 Unknown     5:16 AM     C#, Threading     1 comment   

Hello Everyone, I talked about delegate in my last article. In this article we will talk about multicast delegate.

A Delegate is a type variable that holds the reference of a method and multicast delegate can holds the reference of multiple methods. So basically it's kind of linked list of methods. When we execute the multicast delegate then all the methods which are associated with the multicast delegate will execute in sequence.
How can we create a multicast delegate ?
There is no difference in creation of Delegate and Multicast Delegate. It's just we can associate multiple methods with the same delegate.
 Now the question is how can we associate  multiple methods to a delegate ?
There are two ways of associating multiple methods  -

Delegate.Combine(myDelA, myDelB);
Or
myDelA += MethodB;
Let's see the example -
So now question is How multicast delegate reference to the methods and invoke it ?

There is a method exposed in delegate from which we can fetch the invocation list
and that list returns the collection of all the associated delegates.
 
public delegate int myDel();

        static void Main(string[] args)
        {
            myDel multiCast = MethodC;
            multiCast += MethodD;

            foreach (myDel del in multiCast.GetInvocationList())
            {
                del.Invoke();
            }
        }

        static int MethodC()
        {
            Console.WriteLine("Executing method C.");
            return 1;
        }

        static int MethodD()
        {
            Console.WriteLine("Executing method D.");
            return 1;
        }

So in the above example I have not called invoke method of delegate directly. Instead of fetching all the method info from GetInvocationList() and invoking it one by one. This is the way .Net framework calls the method in sequential way.

Let's say if some of the method throws exception then how multicast delegate handles that situation ?
Have a look on below Example this is the answer of the question -


public delegate int myDel();

        static void Main(string[] args)
        {
            myDel multiCast = MethodC;
            multiCast += MethodD;
            //If you will call this. This will throw exception
            //multiCast.Invoke();

            foreach (myDel del in multiCast.GetInvocationList())
            {
                try
                {
                    del.Invoke();
                }
                catch (Exception)
                {
                    //Handled
                }
            }
        }

        static int MethodC()
        {
            try
            {
                return 1;
            }
            catch (Exception ex)
            {
                return 0;
            }

            throw new Exception();
        }

        static int MethodD()
        {
            Console.WriteLine("Executing method D.");
            return 1;
        }

Hope you like reading this article. Please inbox me in case of any confusion.
Happy Coding :) 
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Calling the Delegates using Invoke(), BeginInvoke() and DynamicInvoke() ?

 Unknown     11:59 PM     C#, Threading     17 comments   


Hello Guys, So in the last article we talked about What is delegate and how can we create a delegate.
In this article we will discuss what are the ways available to call a delegate and what are the differences in between ?
There are different ways in which you can invoke delegates to get a synchronous or an asynchronous behavior.










synchronous -  Using Invoke we can achieve this and in this delegate execute synchronously on the same thread. So in general when you want to invoke a delegate and want to wait for its completion before current thread continues then Invoke is the right choice. Details you can see in this article -


Asynchronous Way -  We can achieve this using BeginInvoke, It means you do not want that main thread  wait for the completion of the delegate. In this scenario the delegate and current thread can work in parallel.

Point to notice here is You can achieve Asynchronous  way using Delegate.BeginInvoke or creating a new thread then Which one to prefer and Why ?

Delegate provides a very less control over async behavior as when you invoke a delegate you can fetch the result using EndInvoke but you cannot terminate the process. While creating a thread you have more control on Async behavior. So in my understanding creating a Thread is better than invoking a delegate in Async way.
Implementation of BeginInvoke -













In the above example we saw how can we invoke a delegate using BeginInvoke.

So now in case GenerateMainXml has to return some value. How can we handle this situation ?
Answer is EndInvoke.
Calling EndInvoke will always block your main thread until it completes the execution. There are two ways of calling EndInvoke. One is as a callback and another one is direct way.
Direct way of calling an EndInvoke() -
 




So in the above example we created a Square number function and assigned it to a delegate. Called using BeginInvoke and on the same delegate called the EndInvoke method to get the results.
There is one problem in this approach. Use case of BeginInvoke is to get asynchronous way of implementing one of the method. But after calling EndInvoke we are telling to main thread to wait until delegates execution completes. Then only we can fetch the results .
So now what is the solution ?
Calling EndInvoke as Callback method. In this way we tell delegate once it completes the execution, call  the callback method and tell us the results. So main thread won't be blocked.








Looks Good :)

DynamicInvoke :  It is similar to Invoke, it invokes a delegate in asynchronous way. The only benefit is it takes  object[] as parameter. So it does boxing and unboxing at run time.







Correct implementation is -















So we can see in the above example we can pass an object array as aparameter in dynamicinvoke and the result will also be a object type. So this is usefule when you are not aware of the type but it will be damn slow. So think before using it.

Hope you like reading the article. Please inbox me in case of any confusion is in your mind.
Happy Coding:)

Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Newer Posts Older Posts Home

About The Author

Unknown
View my complete profile

Total Pageviews

Popular Posts

  • Predicate delegate in C#
    Hello Everyone, In the article we will talk about Predicate delegate. Predicate is also a delegate which encapsulate a method that takes...
  • Clr - Common Language Runtime
    .Net framework provides a run time environment - CLR. Common language runtime takes the IL code from the compiler( language specific) and p...
  • Auto logout chrome extension for Gmail
    Hello Friends, In the last article we learned to create a sample chrome extension. Here we are going to create auto logout Gmail script as...
  • Nagarro Placement Papers..
    Ques.1 :- Seat Reservation prog for the theatre. Write a function for seat allocation for the movie tickets. Total no of seats available are...
  • What does it mean by disconnected data access architecture of ADO.Net?
    ADO.Net introduces the concept of disconnected data architecture. In traditional data access components, you make a connection to the databa...
  • .Net Framework overview
    Hello friends : Here i am writing my first article on .Net framework anyways....So the question is What is .Net Framework ? The .Net fram...
  • Calling the Delegates using Invoke(), BeginInvoke() and DynamicInvoke() ?
    Hello Guys, So in the last article we talked about What is delegate and how can we create a delegate. In this article we will discuss w...
  • C code to Check the string has valid identifier or not in.
    #include #include #include char keyword[][10]={"auto","break","case","char","const","...
  • Garbage Collection - Automatic memory management
    While thinking of this question few things are coming in my mind ~ How .Net reclaims objects and memory used by an application ? So the ans...
  • How to convert 3d array to 1d array ?
    Suppose you have to insert a value at (2,1,0) and the value is :-5 means firstly you have to find the index through (2,1,0) then you have to...

Blog Archive

  • ►  2016 (4)
    • ►  September (2)
      • ►  Sep 03 (2)
    • ►  August (1)
      • ►  Aug 28 (1)
    • ►  April (1)
      • ►  Apr 24 (1)
  • ▼  2015 (12)
    • ▼  September (10)
      • ▼  Sep 30 (1)
        • Predicate delegate in C#
      • ►  Sep 29 (1)
        • Func Delegate in C#
      • ►  Sep 28 (1)
        • Action Delegate in C#
      • ►  Sep 27 (2)
        • Exception Handling in Multicast Delegate ?
        • Multicast Delegate in C#
      • ►  Sep 26 (3)
        • Calling the Delegates using Invoke(), BeginInvoke(...
      • ►  Sep 20 (1)
      • ►  Sep 19 (1)
    • ►  August (1)
      • ►  Aug 16 (1)
    • ►  March (1)
      • ►  Mar 31 (1)
  • ►  2013 (10)
    • ►  June (1)
      • ►  Jun 16 (1)
    • ►  April (1)
      • ►  Apr 21 (1)
    • ►  February (8)
      • ►  Feb 18 (3)
      • ►  Feb 17 (2)
      • ►  Feb 16 (2)
      • ►  Feb 15 (1)
  • ►  2012 (1)
    • ►  May (1)
      • ►  May 27 (1)
  • ►  2010 (22)
    • ►  October (14)
      • ►  Oct 21 (1)
      • ►  Oct 06 (12)
      • ►  Oct 04 (1)
    • ►  April (2)
      • ►  Apr 22 (1)
      • ►  Apr 16 (1)
    • ►  March (1)
      • ►  Mar 30 (1)
    • ►  January (5)
      • ►  Jan 08 (3)
      • ►  Jan 01 (2)
  • ►  2009 (110)
    • ►  December (8)
      • ►  Dec 18 (2)
      • ►  Dec 05 (1)
      • ►  Dec 04 (5)
    • ►  November (1)
      • ►  Nov 27 (1)
    • ►  October (14)
      • ►  Oct 09 (4)
      • ►  Oct 07 (1)
      • ►  Oct 06 (3)
      • ►  Oct 05 (3)
      • ►  Oct 01 (3)
    • ►  September (17)
      • ►  Sep 30 (1)
      • ►  Sep 29 (1)
      • ►  Sep 28 (1)
      • ►  Sep 25 (1)
      • ►  Sep 24 (1)
      • ►  Sep 17 (2)
      • ►  Sep 15 (3)
      • ►  Sep 11 (2)
      • ►  Sep 09 (3)
      • ►  Sep 08 (2)
    • ►  August (31)
      • ►  Aug 31 (1)
      • ►  Aug 27 (3)
      • ►  Aug 26 (1)
      • ►  Aug 25 (2)
      • ►  Aug 24 (1)
      • ►  Aug 22 (2)
      • ►  Aug 21 (3)
      • ►  Aug 20 (2)
      • ►  Aug 19 (3)
      • ►  Aug 18 (1)
      • ►  Aug 16 (1)
      • ►  Aug 12 (2)
      • ►  Aug 11 (1)
      • ►  Aug 10 (3)
      • ►  Aug 07 (4)
      • ►  Aug 06 (1)
    • ►  July (24)
      • ►  Jul 25 (4)
      • ►  Jul 24 (20)
    • ►  April (15)
      • ►  Apr 10 (3)
      • ►  Apr 07 (9)
      • ►  Apr 06 (3)

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments
copyright @ TechGiant 2015. Powered by Blogger.

Disclaimer

This is my personal blog and i write articles on .Net, WPF, C#, OOPS, Threading and other .Net technologies. This is not related to any of my employer and organizations. This is the result of my personal interest.

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Followers

Copyright © A Developer Journey who codes for fun | Powered by Blogger
Design by Hardeep Asrani | Blogger Theme by NewBloggerThemes.com