Skip to main content

Posts

Showing posts from June, 2011

Extension Method C#

Once a type is defined and compiled into a .NET assembly, its definition is, more or less, final. In order to add new members, update members, or remove members we need to recode and recompile the code base into an updated assembly. Or we could use System.Reflection.Emit namespace to reshape a compiled type dynamically. Extension methods allow us to extend the functionality of previously compiled types. Using extension methods, we can add functionality to precompiled types while providing the illusion these methods were there all along. When we create extension methods, the existing precompiled assembly is not literally modified. Rather, the type is extended within the current project. If we package extension methods into a custom .NET *.dll, other applications would need to reference this library to make use of the extensions. To this end, extension methods are really just a way to ‘pretend’ a type has new functionality. The real type is not modified in any way. Why do we need

Implicitly typed local variables

It is not a new feature anymore, but I realized few of my friends still do not know the benefits and need of it. Thus, I feel it is worth writing. This post may not be helpful for you experts!!! Example to start of with and put few questions         public void ImplicitVars()         {             var i = 0;             var s = "Do I know";             Console.WriteLine("i is of type {0}",i.GetType().FullName);             Console.WriteLine("s is of type {0}",s.GetType().FullName);         } Output i is of type System.Int32 s is of type System.String Now add another line after second Console.WriteLine - i = "Error"; public void ImplicitVars() { var i = 0; var s = "Do I know"; Console.WriteLine("i is of type {0}",i.GetType().FullName); Console.WriteLine("s is of type {0}",s.GetType().FullName); i = "Error"; } We will get a compile time error. “Cannot implicitly convert type string to