Sunday 5 April 2015

Action, Func and Predicate Delegate in C#



Action, Func and Predicate Delegate in C#

Delegate is a very powerful feature available in the .NET Framework. In this article, we will explore delegate & its new features which are being introduced in the framework. I will be using Visual Studio 2013 for coding sample code, assuming that you do have basic knowledge of .NET C# code.
I will be explaining the following flavors in these articles:

Action
Ø  Action is a delegate (pointer) to a method, that takes zero, one or more input parameters, but does not return anything.
Ø  When you want a delegate for a function that may or may not take parameters and does not return a value.
Ø  Action is more commonly used for things like List<T>.ForEach: execute the given action for each item in the list..
Ø  I use these often for anonymous event handlers:
Ø  Example
                    button1.Click += (sender, e) => {/* Do Some Work */}

Func

  •  Func is a delegate (pointer) to a method, that takes zero, one or more input parameters, and returns a value (or reference).
  •  When you want a delegate for a function that may or may not take parameters and returns a value.
  • The most common example would be Select from LINQ:
  • Example

                    var result = someCollection.Select( x => new { x.Name, x.Address });

Predicate is a special kind of Func often used for comparisons.

  •  Predicate is a delegate that takes generic parameters and returns bool
  • When you want a specialized version of a Func that takes evaluates a value against a set of criteria and returns a boolean result (true for a match, false otherwise).
  • Though widely used with Linq, Action and Func are concepts logically independent of Linq. C++ already contained the basic concept in form of typed function pointers.
  •   Predicate<T> is a delegate that takes a T and returns a bool.
    It's completely equivalent to Func<T, bool>.
  • Predicate is just a special cased Func<T, bool> really, introduced before all of the Func and most of the Action delegates came along
  • Predicate is mostly used in List<T> for methods like FindAll and RemoveAll.



 
Here is a small example for Action and Func without using Linq:


class Program
{
    static void Main(string[] args)
    {
        Action<int> myAction = new Action<int>(DoSomething);
        myAction.Invoke(123);           // Prints out "123"

        Func<int, double> myFunc = new Func<int, double>(CalculateSomething);
        Console.WriteLine(myFunc(5));   // Prints out "2.5"
    }

    static void DoSomething(int i)
    {
        Console.WriteLine(i);
    }

    static double CalculateSomething(int i)
    {
        return (double)i/2;
    }
}


Conclusion:

The difference between Func and Action is simply whether you want the delegate to return a value (use Func) or doesn't (use Action).


Happy Programming!!
 
Don’t forget to leave your feedback and comments below!
 
If you have any query mail me to Sujeet.bhujbal@gmail.com     
 
Regards
Sujeet Bhujbal
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------

Interview Questions & Answers for Prism WPF



Interview  Questions & Answers for Prism WPF

1. Define PRISM

This a framework used for developing complex applications for WPF, Silverlight or Windows Phone. The framework utilizes MVVM, Command patterns, DI, and Separation of Concerns to get loose coupling.

2. What are the benefits of PRISM?

Modular development: - As we are developing components as independent units we can assign these units to different developers and do modular parallel development. With parallel development project will be delivered faster.

High reusability: - As the components are developed in individual units we can plug them using PRISM and create composed UI in an easy way.


3. What is Bootstarpper?

   Bootstrapper is a class starts the shell. For example bootstrapper for a prism MEF application
   which inherits from MefBootstrapper.

Example

 class Bootstrapper : UnityBootstrapper
    {
        protected override DependencyObject CreateShell()
        {
            return Container.Resolve<MainWindow>();
        }

        protected override void InitializeShell()
        {
            Application.Current.MainWindow.Show();
        }
    }

4. Is PRISM a part of WPF?
    No, PRISM is a separate installation.

5. Does it provide dependency injection? Does it relate to MEF at all in this way?

Yes. It originally included Unity, but the latest release includes using MEF for DI.


6. What is Module?


    Modules are classes that implement the IModule interface. A module in Prism is simply a loosely coupled functional unit in form of a class library project that typically represents a set of related concerns and includes a collection of related components, such views, view models, models and other classes.

Example

[Module(ModuleName = "TestModule", OnDemand = false)]
[ModuleDependency("ModuleDockModule")]
public class TestModuleModule : IModule
{ ...


7. How many ways modules can be registered?


   Modules can be registered from  -
  • Directly inside code
  • Using Configuration
  • Using Directory Inspection

8. What is Module Dependency


   Module can have dependency on other module. Prism provides module dependency management.
We need to set DependsOn property in a ModuleInfo class instance before adding module. DependsOn requires a collection of module names.
Example: 

[Module(ModuleName = ModuleNames.ModuleA)]    
[ModuleDependency(ModuleNames.ModuleD)]
public class ModuleAModule : IModule
{


9. What is Container or Dependency Injection Container?

   Core Prism library is container agnostic. The following are examples of containers that are used as
   dependency injection containers in Prism.
  • ModularityWithMef
  • ModularityWithUnity 



10. How do you register modules?
    Bootstrapper override CreateModuleCatalog and ConfigureModuleCatalog methods.


11. By default does MEF create singleton instance of objects?
   Yes, by default MEF creates singleton instance.

12. How to specify so that MEF does not create singleton instance?

    Decorate with attribute to indicate that the created instance is not shared.
    [PartCreationPolicy(CreationPolicy.NotShared)]



Happy Programming!!
Don’t forget to leave your feedback and comments below!


Regards
Sujeet Bhujbal
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------