C# – Example when and why to use delegates

Why to use Delegate:
All of us have been exposed to event driven programming of some sort or the other. A delegate can be seen as a placeholder for a/some method(s) and used to pass methods as arguments to other methods. Event handlers are nothing more than methods that are invoked through delegates. You create a custom method, and a class such as a windows control can call your method when a certain event occurs.

Delegates in c# are type safe objects which are used to hold reference of one or more methods. Delegate represents references to methods with a particular parameter list and return type. When you instantiate a delegate, you can associate its instance with any method with a compatible signature and return type.

An interesting and useful property of a delegate is that it does not know or care about the class of the object that it references. Any object will do; all that matters is that the method’s argument types and return type match the delegate’s. This makes delegates perfectly suited for “anonymous” invocation.

What is the use of Delegates?
Suppose if you have multiple methods with same signature (return type & number of parameters) and want to call all the methods with single object then we can go for delegates.

Delegates are two types
–  Single Cast Delegates
–  Multi Cast Delegates

Single Cast Delegates:
Single cast delegate means which hold address of single method like as explained in above example.

Example:
public delegate int DelegatSample(int a,int b);

public class Sampleclass
{
public int Add(int x, int y)
{
return x + y;
}
public int Sub(int x, int y)
{
return x – y;
}
}
class Program
{
static void Main(string[] args)
{
Sampleclass sc=new Sampleclass();

DelegatSample delgate1 = sc.Add;
int i = delgate1(10, 20);
Console.WriteLine(i);
DelegatSample delgate2 = sc.Sub;
int j = delgate2(20, 10);
Console.WriteLine(j);
}
}

Output:
Add Result : 30
Sub Result : 10

Multicast Delegates:
Multi cast delegate is used to hold address of multiple methods in single delegate. To hold multiple addresses with delegate we will use overloaded += operator and if you want remove addresses from delegate we need to use overloaded operator -=

Multicast delegates will work only for the methods which have return type only void. If we want to create a multicast delegate with return type we will get the return type of last method in the invocation list

Example:
public delegate void MultiDelegate(int a,int b);

public class Sampleclass
{
public static void Add(int x, int y)
{
Console.WriteLine(“Addition Value: “+(x + y));
}
public static void Sub(int x, int y)
{
Console.WriteLine(“Subtraction Value: ” + (x – y));
}
public static void Mul(int x, int y)
{
Console.WriteLine(“Multiply Value: ” + (x * y));
}
}
class Program
{
static void Main(string[] args)
{
Sampleclass sc=new Sampleclass();
MultiDelegate del = Sampleclass.Add;
del += Sampleclass.Sub;
del += Sampleclass.Mul;
del(10, 5);
Console.ReadLine();
}
}

Output
Addition Value : 15
Subtraction Value : 5
Multiply Value : 50

Delegates have the following properties:

  1. Delegates are like C++ function pointers but are type safe.
  2. Delegates allow methods to be passed as parameters.
  3. Delegates can be used to define callback methods.
  4. Delegates can be chained together; for example, multiple methods can be called on a single event.
  5. C# version 2.0 introduced the concept of Anonymous Methods, which allow code blocks to be passed as parameters in place of a separately defined method. C# Version 3.0 introduced lambda expressions as a more concise way of writing inline code blocks. Both anonymous methods and lambda expressions (in certain contexts) are compiled to delegate types. Together, these features are now known as anonymous functions.

 

Share this:
Share

Asp.Net – what is query string in asp.net with example

Querystring is a kind of variable which can be used to pass a value from one page to another page. hence there are several way to pass value from one page to another page. but we are describing on this article.

Querystring variable pass with variable with “?”

For example: http://www.abc.com/test.html?var1=this is query string variable value.

In the above example “var1” is variable name and “this is query string variable value.” the variable value. we can use this querystring in asp.net as follows.

string var1=Request.QueryString[“var1”];

We can use mutliple querystring variable as well. first variable would use with “?” and other variable will use with “&”

For example: http://www.abc.com/test.html?var1=this is first variable&var2=this is second variable&var3=this is third variable

In the above example “var1”, “var2” and “var3” are querystring variable and we can fetch the values of query string value in asp.net as follows.

string var1=Request.QueryString[“var1”];
string var2=Request.QueryString[“var2”];
string var3=Request.QueryString[“var3”];

Share this:
Share

Dot Net Coding Standard: UI Control Naming Conventions

UI controls would use the following prefixes.  The primary purpose was to make code more readable.

Control Type Prefix
Button btn
CheckBox chk
CheckedListBox lst
ComboBox cmb
ContextMenu mnu
DataGrid dg
DateTimePicker dtp
Form suffix: XXXForm
GroupBox grp
ImageList iml
Label lb
ListBox lst
ListView lvw
Menu mnu
MenuItem mnu
NotificationIcon nfy
Panel pnl
PictureBox pct
ProgressBar prg
RadioButton rad
Splitter spl
StatusBar sts
TabControl tab
TabPage tab
TextBox tb
Timer tmr
TreeView tvw
Share this:
Share

OOP – What is abstract ?

The abstract modifier can be used with classes, methods, properties, indexers, and events.

Use the abstract modifier in a class declaration to indicate that a class is intended only to be a base class of other classes.

Abstract classes have the following features:

  1. An abstract class cannot be instantiated.
  2. An abstract class may contain abstract methods and accessors.
  3. It is not possible to modify an abstract class with the sealed modifier, which means that the class cannot be inherited.
  4. A non-abstract class derived from an abstract class must include actual implementations of all inherited abstract methods and accessors.
  5. Use the abstract modifier in a method or property declaration to indicate that the method or property does not contain implementation.

Abstract methods have the following features:

  • An abstract method is implicitly a virtual method.
  • Abstract method declarations are only permitted in abstract classes.
  • Because an abstract method declaration provides no actual implementation, there is no method body; the method declaration simply ends with a semicolon and there are no braces ({ }) following the signature. For example:public abstract void MyMethod();
  • The implementation is provided by an overriding method, which is a member of a non-abstract class.
  • It is an error to use the static or virtual modifiers in an abstract method declaration.
  • Abstract properties behave like abstract methods, except for the differences in declaration and invocation syntax.
  • It is an error to use the abstract modifier on a static property.
  • An abstract inherited property can be overridden in a derived class by including a property declaration that uses the override modifier.
  • An abstract class must provide implementation for all interface members.

An abstract class that implements an interface might map the interface methods onto abstract methods.

Example:

interface I
{
void M();
}

abstract class C: I
{
public abstract void M();
}

In this example, the class MyDerivedC is derived from an abstract class MyBaseC. The abstract class contains an abstract method, MyMethod(), and two abstract properties, GetX() and GetY().

Example:
// abstract_keyword.cs
// Abstract Classes

using System;
abstract class MyBaseC // Abstract class
{
protected int x = 100;
protected int y = 150;
public abstract void MyMethod(); // Abstract method

public abstract int GetX // Abstract property
{
get;
}

public abstract int GetY // Abstract property
{
get;
}
}

class MyDerivedC: MyBaseC
{
public override void MyMethod()
{
x++;
y++;
}

public override int GetX // overriding property
{
get
{
return x+10;
}
}

public override int GetY // overriding property
{
get
{
return y+10;
}
}

public static void Main()
{
MyDerivedC mC = new MyDerivedC();
mC.MyMethod();
Console.WriteLine(“x = {0}, y = {1}”, mC.GetX, mC.GetY);
}
}

Output
x = 111, y = 161

In the preceding example, if you attempt to instantiate the abstract class by using a statement like this:

MyBaseC mC1 = new MyBaseC(); // Error

you will get the following error message:
Cannot create an instance of the abstract class ‘MyBaseC’.

Share this:
Share

C# – What is readonly variable and how to use it

The readonly keyword is a modifier that you can use on fields. When a field declaration includes a readonly modifier, assignments to the fields introduced by the declaration can only occur as part of the declaration or in a constructor in the same class.

You can assign a value to a readonly field only in the following contexts:

When the variable is initialized in the declaration, for example:

public readonly int y = 5;

For an instance field, in the instance constructors of the class that contains the field declaration, or for a static field, in the static constructor of the class that contains the field declaration. These are also the only contexts in which it is valid to pass a readonly field as an out or ref parameter.

Example

// Readonly fields

using System;
public class ReadOnlyTest
{
class MyClass
{
public int x;
public readonly int y = 25; // Initialize a readonly field
public readonly int z;
public MyClass()
{
z = 24; // Initialize a readonly instance field
}

public MyClass(int p1, int p2, int p3)
{
x = p1;
y = p2;
z = p3;
}
}

public static void Main()
{
MyClass p1= new MyClass(11, 21, 32); // OK
Console.WriteLine(“p1: x={0}, y={1}, z={2}” , p1.x, p1.y, p1.z);
MyClass p2 = new MyClass();
p2.x = 55; // OK
Console.WriteLine(“p2: x={0}, y={1}, z={2}” , p2.x, p2.y, p2.z);
}
}

Output:
p1: x=11, y=21, z=32
p2: x=55, y=25, z=24

In the preceding example, if you use a statement like this:
p2.y = 66; // Error

you will get the compiler error message:
The left-hand side of an assignment must be an l-value
which is the same error you get when you attempt to assign a value to a constant.

Note:

  • The readonly keyword is different from the const keyword.
  • A const field can only be initialized at the declaration of the field.
  • A readonly field can be initialized either at the declaration or in a constructor.

Therefore, readonly fields can have different values depending on the constructor used. Also, while a const field is a compile-time constant, the readonly field can be used for runtime constants as in the following example:

public static readonly uint l1 = (uint) DateTime.Now.Ticks;

Share this:
Share