Skip to main content

Notes on C#–Part - I

1. Covariant and Contravariant?

a. Covariant is converting from wider (double) to narrower (float)
b. Contravariant is converting from narrower (float) to wider (double)
c. Invariant is not able to convert.

2. Immutable Objects are objects whose state cannot be altered externally or internally.

3. In C# 4.0 you can now do the following –

If Manager inherits from Employee then
IEnumerable<Manager> mgrs = GetManagers();
IEnumerable<Employee> emps = mgrs;
This is because CLR now supports defining IEnumerable<out T>
This is called Covariance.
Next in-case of IComparable
IComparable<Employee> empComparer = GetEmployeeComparer();
IComparable<Manager> mgrComparer = empComparer
This is because CLR now supports defining IComparable<in T>
This is called Contravariant.

4. C# 4.0 now has dynamic built in type. This is not resolved by the compiler but it left for resolution until run time. So C# now supports dynamic late binding. The infrastructure that supports these dynamic operations at run time is called Dynamic Language Runtime or DLR. DLR runs on top of CLR.

So now instead of doing –
Object o = GetObject();
Type t = o.GetType();
Object result = t.InvokeMember(“MyMethod”,BindingFlags.InvokeMethod,null,o,new object[] {});
We can simply say the following –
Dynamic o = GetObject();
Int I = o.MyMethod();
And the above line will compile fine.

5. C# 4.0 now supports optional parameters with default values. So for example if we had a method like –

Public void MyMethod(int duration, int? iteration = null, bool reverse = false);
Then you can now call this method in any of the following ways –
MyMethod(55);
MyMethod(55, reverse: true);
MyMethod(55, null);

6. Partial classes – It is possible to split the definition of class or interface or struct or a method over two or more files.

a. Use partial keyword to do this
b. Nested types can be defined as partial
c. Members, interfaces, xml comments and attributes are all merged from parts of the partial types
d. Partial method declarations must return void

7. Static classes – Classes that cannot be instantiated.

a. You access the members by using Class Name itself.
b. Static constructor is called only once
c. Class remains in memory for the lifetime of the application domain.
d. Is sealed
e. Contains only static members.
f. Cannot contain instance constructor.

8. Nullable types are instance of System.Nullable<T> struct.

a. T should be of value type.
b. It represents complete range of value of the underlying value type plus an additional null value.
c. Use HasValue property to check if it contains a value or if it is null
d. Value property returns actual value
e. You can use ? suffix in C# with value type to make it nullable eg – int? x = 10;

9. Null Coalescing operator (??) – It’s a simple operator which is used to check for null and assign an alternate value. Eg – a = b ?? 0; means a = b == null ? 0 : b; Operand b should be either a nullable type or a reference type for this operator to work.

10. Delegate – It is a type that defines a method signature. During instantiation you can associate it with a method of matching signature. Eg – public delegate int SomeDelegate(int x, int y);

a. They are used to pass methods as arguments to other methods.
b. Event Handlers are methods that are invoked through delegates.
c. They are like C++ function pointers but are type safe.
d. Used to define callback methods
e. Delegates can be chained together.
f. Delegates with more than one method in their invocation list derive from MultiCastDelegates.
g. A Delegate can be associated with a named method or an anonymous method.

11. Delegate vs Interfaces

a. Use delegate when event design pattern is to be used
b. Use delegate when a class needs more than one implementation of a method
c. Use delegate when it is desirable to encapsulate a static method
d. Use interfaces to group related methods
e. Use interfaces when a class needs only one implementation of a method

12. Anonymous functions – This is an inline statement or expression that can be used wherever a delegate type is expected.

13. There are two types of anonymous functions –

a. Lambda Expressions
b. Anonymous Methods

14. Lambda Expressions – is an anonymous function that can contain expressions and statements, and can be used to create delegates or expression trees.

a. All lambda expressions use lambda operator => called ‘goes to’
b. Left side of lambda operator specifies input and the right side is for the expression.
c. Eg –
When using with delegates -
delegate int myDelegate(int i);
myDelegate delegateInstance = x => x*x;
delegateInstance(5) // this will give 25.
When using with Expressions (Expression<Func>) –
Expression<myDelegate> myExp = x => x*x;
d. Examples of Expression Lambdas –
(x,y) => x == y;
(int x, string s) => s.length > x;
() => SomeMethod();
e. Variables declared in a method and consumed / used inside a lambda expression are captured and garbage collected only when the delegate that references it goes out of scope.
f. Return statement inside a lambda expression does not cause the enclosing method to return.

15. Anonymous Methods – Anonymous methods enable you to omit parameter list which is not possible with Lambda expressions.

a. Example – button1.click += delegate(object sender, EventArgs e) {MessageBox.Show(‘Click’); };

16. Iterators – An iterator is a method, get accessor or operator that perform a custom iteration over an array or collections class by using the yield keyword.

a. The Yield return statement causes an element in the source sequence to return immediately to the caller before the next statement in the source sequence is accessed.
b. Iterator method is translated into a nested class that is in effect a state machine by the compiler.
c. Iterators are invoked by using foreach statement in the client
d. Yield break is used to end the iteration
e. You can have multiple iterators in a class. They should have unique names.
f. Iterators are the basis for the deferred execution behaviour in the LINQ queries.
g. Most common way to create an Iterators is to implement the GetEnumerator() method on the IEnumerable interface. This allows you to use the foreach statement on the type.
h. Example –
Public class MonthOfYear : IEnumerable
{
String[] months = {‘Jan’,’Feb’,’Mar’,’Apr’,’May’,’Jun’,’Jul’,’Aug’,’Sep’,’Oct’,’Nov’,’Dec’};
Public IEnumerator GetEnumerator()
{for(int i=0; i<months.length;i++) yield return months[i];}
}
i. An Iterator can also have parameters like –
Public IEnumerator GetAlternateEnumerator(int start, int end);
j. A named iterator like above has to be invoked explicitly like –
foreach(int I in SomeClassObject.GetAlternateEnumberator(10,15)) {…};

References –

New Features in C# 4.0 - http://msdn.microsoft.com/en-us/magazine/ff796223.aspx
Delegates - http://msdn.microsoft.com/en-us/library/ms173171.aspx
Lambda Expressions - http://msdn.microsoft.com/en-us/library/bb397687.aspx
Iterators - http://msdn.microsoft.com/en-us/library/dscyy5s0.aspx

Comments

Popular posts from this blog

Notes on Castle MonoRail

  Sometime back I was doing a small POC on Castle MonoRail. So here are my quick notes on this. MonoRail is an MVC Framework from Castle inspired by ActionPack. MonoRail enforces separation of concerns with Controller handling application flow, models representing data and View taking care of the presentation logic. To work with MonoRail you need Castle Assemblies. It also utilizes nHibernate You can use Castle MonoRail Project Wizard or create the project manually. Project structure – Content Css Images Controllers HomeController.cs Models Views Home \ index.vm Layouts \ Default.vm ...

Workflow Foundation 4 - Part 3 - Data storage and management

This is my third post on WF4. First one was an introductory post on WF4 and in second one we focused on executing workflows. In the this post I am going to focus on the topic of data storage and management. Every business process or flow depends on data. When you think of data there are three elements to it as listed below - Variables - for storing data Arguments - for passing data Expressions - for manipulating data. Let us first look at the variables. Variables are storage locations for data. Variables are declared before using them just like in any other languages like C# or VB.Net. Variables are defined with a specific scope. When you create a variable in an activity the scope of the variable becomes that activity's scope. Variables can also have access modifiers like None, Mapped or ReadOnly. Let us look at an example where we will create two variables and assign a scope to them along with access modifiers. //Declare a sequence activitiy Sequence seqWf = new Sequence(); //de...

Introduction to Workflow Foundation 4 (WF4)

I finally decided to pick-up my blogging once more. Since I have been trying to learn Windows Workflow Foundation 4 (WF4) I thought I might as well start off with this topic. WF4 is a development framework that enables you to create a workflow and embed it in a .Net application. It is neither an executable application nor a language. It provides a set of tools for declaring a workflow, activities to create your logic and to define control flow and a runtime for executing the resulting application definition. It also provides services for persistence of state, tracking and bookmarking. You can create your workflow directly in code, in mark-up or in a combination of both. Workflow provide us with two major advantages - Creating unified application logic. Making application logic scalable. Workflow Authoring styles - Sequential Workflow executes a set of contained activities in a sequential manner. Workflow Foundation was introduced in the .Net 3.0 and updated in 3.5. In .net 4 it has bee...