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

Health Framework - Apple vs Android

In the past few years we have seen mobile and its apps rise and shine transforming many industries in its wake. However, the growth in health and fitness category has been less spectacular at 49% compared to overall mobile app industry which grew at 115% in the year 2013 (source Flurry Analytics). A few years ago Microsoft and Google attempted to make inroads into the health and fitness sector by bringing web based products to store and maintain health and fitness information like MS HealthVault and Google Health with not so spectacular results. Next came innovations by Fitbit in the wearables sector for activity tracking, in 2011 and 2012 they introduced first wireless activity trackers to sync using Bluetooth. This was followed by the entry of Jawbone into health sector with its announcements of Up wristband and accompanying app. These have had better success resulting in many startups joining the wearables product bandwagon.  Late to the stage almos...

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 ...

Quick notes on Git

  I have been away from writing anything for a long time and instead have been fooling around with other stuffs like just plain reading, growing mustache, trying to learn swimming, trying to learn to play acoustic guitar and trying my hands at photography. To be honest I have not given up on them yet but neither have I been able to hang on to them in a disciplined manner. So here I am back to my writing after a long gap. This time its going to be quick notes on Git . Git is a file repository. As opposed to other repositories like SVN Git thinks of its data more like a snapshot of a mini filesystem. All operations in Git are local. (Entire history of the project is stored locally in your working directory) Browsing project history. Viewing all changes to a file. Git uses Checksum to track repository items Everything in Git is check-summed It uses SHA-1 hash for generating check sum values All a...