Generics in C#
Generics in C#
contents
• Introduction to generics
• Benefits of generics
• Generic Class
• Generic Interface
• Generic Method
• Generic Delegate
Introduction to Generics
• Generic are type safe. You get compile time errors if you try to use a
different type of data than the one specified in the definition.
class MyGenericClass<T>
{
private T genericMemberVariable;
public MyGenericClass(T value)
{
genericMemberVariable = value;
}
public T genericMethod(T genericParameter)
{
Console.WriteLine("Parameter type: {0}, value: {1}", typeof(T).ToString(),genericParameter);
Console.WriteLine("Return type: {0}, value: {1}", typeof(T).ToString(), genericMemberVariable);
Return genericMemberVariable;
}
public T genericProperty
{
get; set;
}
}
Generic Delegates
• The delegate defines the signature of the method which it
can invoke. A generic delegate can be defined the same way
as delegate but with generic type.
• Anonymous methods in C# can be defined using the delegate keyword and can be assigned to a variable of delegate type.
• Example:
• Anonymous methods can access variables defined in an outer
function.
• Anonymous methods can also be passed to a method that accepts
the delegate as a parameter.
• Anonymous methods can be used as event handlers:
saveButton.Click += delegate(Object o, EventArgs e)
{
System.Windows.Forms.MessageBox.Show("Save
Successfully!");
};
Typical usage of an anonymous method is to assign it to an event.
Limitations
• It cannot contain jump statement like goto, break or continue.
• It cannot access ref or out parameter of an outer method.
• It cannot have or access unsafe code.
• It cannot be used on the left side of the is operator.
Points to Remember
• Anonymous method can be defined using the delegate keyword
• Anonymous method must be assigned to a delegate.
• Anonymous method can access outer variables or functions.
• Anonymous method can be passed as a parameter.
• Anonymous method can be used as event handlers.