Friday, August 26, 2011

Delegate vs. Interface


In this post I will explain some distinct features of delegate and interface.

All of you might aware about delegate and interface functionality in .Net. The similar kind of functionality can be achieved using both delegate and interface but both have their unique features too. So the question is when to use interface and when to use delegate?

Let’s start understanding using simple example.

Example 1 - Using interface

public interface IMyInterface
{
     void MyMethod(string name);
}
public class MyClass : IMyInterface
{
     public void MyMethod(string name)
     {
         Console.WriteLine("Hello " + name);
     }
}
public static void Main()
{
IMyInterface iCall = new MyClass();
iCall.MyMethod("Mitesh"); //Output: Hello Mitesh
}

Example 2 - Using delegate

public class MyClass
{
    public void MyMethod(string name)
    {
        Console.WriteLine("Hello " + name);
    }
}
public delegate void MyDelegate(string name);
public static void Main()
{
MyClass cls = new MyClass();
       MyDelegate d = cls.MyMethod;
       d("Mitesh"); //Output: Hello Mitesh
}

Output of example 1 and 2 both are same but both example uses different concept example 1 is using Interface and example 2 is using delegate.

Let’s understand when to use Delegate and when to use Interface?

Use Delegate when -

  • You need to use multicast capability.
  • You want to wrap static methods.
  • Delegate can be used from anywhere in the scope they visible.
  • An event pattern is used.
  • You want to use anonymous methods.


Use Interface when -

  • A class needs only one implementation of method.
  • You want to use inheritance feature because interface can inherit from other interface.
  • You want to avoid method pointers overhead. When you call method using delegate it first scan through before executing it but in case of interface it directly calling method. It has some significance performance improvements.
  • Multiple kind of events are supported and need to implements all of them

See also


Thursday, August 25, 2011

Partial Methods in C#


All of us know that partial type allows us to split definition of type across multiple files but do you know C# also provides supports for partial methods too. Partial methods are used when your code is auto generated by code generation tool. The tool will write only method definition and leave the implementation of for developer if they want to customize.

Basically partial method contains two parts, method definition and implementation. The definition is mostly written by code generation tool and implementation is written manually by developer. If no implementation provided then compiler removes method signature at compile time.

Below things should be kept in mind while creating partial method

  • Partial methods must be declared inside a partial class.
  • Partial methods can have ‘ref’ parameters but not ‘out’ parameters.
  • Partial methods are implicitly private therefore they can’t be Virtual.
  • Partial methods must be void.

Below example demonstrate use of partial methods.

public partial class MyClass
{
    partial void MyMethod();
}
public partial class MyClass
{
    public MyClass()
    {
        MyMethod();
    }
    partial void MyMethod()
    {
        Console.WriteLine("Hello");
    }
}


Hope you like this Tip. 


Thanks for reading. Take Care.


See also
How to use Keyword as an identifier
How to check Arithmetic Operation Overflow

Wednesday, August 24, 2011

Checking Arithmetic Operation Overflow


Arithmetic overflow exception can be checked and prevented for integral type using checked and unchecked operator.

Checked Operator enforce overflow checking when an integral expression exceeds the limitation of that type. By default constant expression generates compile-time errors and non-constant expressions are checked at runtime and throw an error based on compiler option.

public static void Main()
{
             
       int x = int.MaxValue +1; // Compile time error
      
       int a = 123456789;
       int b = 123456789;
      
       int c = a * b; // Throws error based on compiler
                         setting or default settings
      
}

Let’s see, How to use checked operator in this scenario?

public static void Main()
{
      
       int a = 123456789;
       int b = 123456789;
      
       try
       {
              checked {
                           int c = a * b;
                     }
       }
       catch (System.OverflowException ex)
       {
              Console.WriteLine(ex.ToString());
       }
}
Output:








Unchecked Operator –
suppress overflow exceptions while performing arithmetic operations on integral types.

public static void Main()
{
      
int x = unchecked(int.MaxValue +1); // Supresses Overflow
                                   Exception @ compile-time
      
       int a = 123456789;
       int b = 123456789;
      
      
       unchecked
{
              int c = a * b; // Supresses Overflow Exception @ run-time
       }
      
}

If checked or unchecked both operator not specified on arithmetic operation then default setting of compiler will be applied and depend on that it throws an error message on overflow. 


See also
How to use keyword as an Identifier (variable)

Tuesday, August 23, 2011

Use keyword as an identifier in C#


Keywords are reserved by compiler so you can’t use it as identifier in your application. If you really need to use keyword as an identifier in your application you can achieve this using @ symbol. Let’s have a look on below example.

public class class //Illegal
{
       public int int =5; // Illegal
}

In above code snippet I have used ‘class’ and ‘int’ as an identifier which is illegal we can’t use keywords as an identifier. If you want to use keyword as identifier you have to use @ prefix with keyword see below example.

public class @class
{
       public int @int = 5;
}


public class MyClass
{
       public static void Main()
       {
              @class cls = new @class();
              Console.WriteLine(cls.@int.ToString());
       }
}
Output
5

This way you can use keyword as an identifier in your application.

Note – Some keywords can be used without using @ prefix like from, where, orderby, yield, var, join etc.

public static void Main()
{
       int where = 5;
       Console.WriteLine(where.ToString());
}

Monday, August 22, 2011

Triggers in WPF


Triggers are collection of setters and execute when condition met. Triggers are part of Style and can be defined inside style. For more information about Style you can go through my article on Style. Five types of Triggers are available in WPF
  • Trigger (Property Trigger)
  • MultiTrigger (Multiple Property Trigger)
  • DataTrigger
  • MultiDataTrigger
  • EventTrigger

Trigger

These triggers are simple triggers and can set any dependency property. Trigger defines property and value. If property contains specified value then the setter action defined inside trigger will execute.

<Window.Resources>
<Style TargetType="Button">
    <Style.Triggers>
        <Trigger Property="IsMouseOver" Value="True">
            <Setter Property="FontSize" Value="20" />
            <Setter Property="FontWeight" Value="Bold" />
            <Setter Property="Foreground" Value="Red" />
        </Trigger>
    </Style.Triggers>
</Style>
</Window.Resources>
<StackPanel>
    <Button Content="Click Me!" Height="40" Width="150" Margin="5" />
</StackPanel>








As per above code, When IsMouseOver property value is true the defined setter action inside trigger will execute.

MultiTrigger

This is similar to Trigger but combines multiple conditions and all the condition must met to execute setter collection defined in multitrigger.

<Window.Resources>
<Style TargetType="Button">
    <Style.Triggers>
        <MultiTrigger>
            <MultiTrigger.Conditions>
                <Condition Property="IsDefault" Value="True" />
                <Condition Property="IsMouseOver" Value="True" />
            </MultiTrigger.Conditions>
            <MultiTrigger.Setters>
                <Setter Property="FontSize" Value="20" />
                <Setter Property="FontWeight" Value="Bold" />
                <Setter Property="Foreground" Value="Red" />
            </MultiTrigger.Setters>
        </MultiTrigger>
    </Style.Triggers>
</Style>
</Window.Resources>
<StackPanel>
    <Button Content="Click Me!" IsDefault="True" 
            Height="40" Width="150" Margin="5" />
</StackPanel>








As per above code, When IsDefault and IsMouseOver both properties value set to true the defined setter action inside multitrigger will execute.


DataTrigger

Data triggers are similar to normal trigger except that they can be triggered by any property rather than just only dependency property. In data trigger we need to specify binding instead of property name.

<Window.Resources>
<Style TargetType="Button">
    <Style.Triggers>
        <DataTrigger  Binding="{Binding
                      RelativeSource={RelativeSource Self},
                      Path=Content}" Value="Click Me!">
            <DataTrigger.Setters>
                <Setter  Property="FontSize" Value="20" />
            </DataTrigger.Setters>
        </DataTrigger>
    </Style.Triggers>
</Style>
</Window.Resources>
<StackPanel>
    <Button Content="Click Me!"
            Height="40" Width="150" Margin="5" />
</StackPanel>









As per above code, Data trigger checks value of Content property of Button and if value matches then it will execute setter block of data trigger. As per above example Button content is 'Click Me!' which matches the value mentioned in data trigger so it will execute setter block. In data trigger binding you can use any property of control or entity.

MultiDataTrigger

This is similar to DataTrigger but combines multiple conditions and all the condition must met to execute setter collection defined in MultiDataTrigger.

<Window.Resources>
<Style TargetType="Button">
    <Style.Triggers>
        <MultiDataTrigger>
            <MultiDataTrigger.Conditions>
                <Condition  Binding="{Binding
                  RelativeSource={RelativeSource Self},
                  Path=Content}" Value="Click Me!" />
                <Condition  Binding="{Binding
                  RelativeSource={RelativeSource Self},
                  Path=IsDefault}" Value="True" />
            </MultiDataTrigger.Conditions>
            <MultiDataTrigger.Setters>
                <Setter  Property="FontSize" Value="20" />
            </MultiDataTrigger.Setters>
        </MultiDataTrigger>
    </Style.Triggers>
</Style>
</Window.Resources>
<StackPanel>
<Button Content="Click Me!" IsDefault="True"
        Height="40" Width="150" Margin="5" />
</StackPanel>








As per above code, When Content property and IsDefault property value match with the value mentioned in data trigger then the setter collection of MultiDataTrigger will execute. Both conditions must match.

EventTriggers

Event triggers are little different than other triggers. It depends on Routed Event. When certain routed event fires the event triggers action will execute. Instead of setter collection EventTrigger have Action collection. Inside action you can specify Animation. Inside action storyboard can be specified. I will explain about Animation and Storyboard in detail in my later post.

<Window.Resources>
<Style TargetType="Button">
<Style.Triggers>
    <EventTrigger RoutedEvent="MouseEnter">
        <EventTrigger.Actions>
            <BeginStoryboard>
                <Storyboard>
                    <DoubleAnimation
                        Duration="0:0:0.5"
                        Storyboard.TargetProperty="Width"
                        To="200"  />
                </Storyboard>
            </BeginStoryboard>
        </EventTrigger.Actions>
    </EventTrigger>
    <EventTrigger RoutedEvent="MouseLeave">
        <EventTrigger.Actions>
            <BeginStoryboard>
                <Storyboard>
                    <DoubleAnimation
                        Duration="0:0:0.5"
                        Storyboard.TargetProperty="Width"
                        To="150" />
                </Storyboard>
            </BeginStoryboard>
        </EventTrigger.Actions>
    </EventTrigger>
</Style.Triggers>
</Style>
</Window.Resources>
<StackPanel>
<Button Content="Click Me!"
Height="40" Width="150" Margin="5" />
</StackPanel>


On Mouse Enter




On Mouse Leave











As per above code, MouseEnter and MouseLeave event trigger is specified. So whenever these events fires the EventTriggerAction will get execute. In above example Button width animation is specified. So when mouse enters inside button area the width of button will set to 200 and on mouse leave set back to 150.


See also