essential language features
Post on 15-Jun-2015
74 Views
Preview:
TRANSCRIPT
Essential Language Features
Anoop K. C.anoop@baabte.comwww.facebook.com/
anoopbaabtetwitter.com/anoop_baabtein.linkedin.com/in/
anoopbaabte/+91 9746854752
Automatically Implemented Properties
Consider a class “baabtraStudent” with the 3 properties name, marks and isPromotable . Consider the following code to implement the class.
If we have a closer look at the implementation of properties, properties name and marks have get and set methods implemented in the usual way whereas the boolean property isPromotable is implemented as a read-only property and the get accessor of isPromotable is implemented with some logic.
The logic is “the student is promotable (isPromotable returns true) only when his marks are greater than 60”
Leaving the isPromotable property and if we look at the other two, there is no logic in the get and set accessors. So if we have 10 or 20 or more such properties we will have to write a lot of code to implement all these which will actually take away a lot from the developers’ time.
The concept of auto-implemented properties removes this hassle by making the property declaration in a single line of code which will look like
Public string name { get; set; }
With such a declaration the compiler will automatically implement the get and set accessors of the property. So that our earlier implementation of the baabtraStudent class can be re-written as
This enhances the code maintainability by a greater degree and removes the need of writing a lot of code to implement the properties.
Summary auto implemented properties can only be used when the implementation of
property (get and set accessors) need no additional logic
Auto implemented properties reduce the amount of code that needs to be written
We don’t have to explicitly declare a field for an auto implemented property.
when we use auto-implemented properties, the compiler creates a private, anonymous field that can only be only be accessed through the property’s get and set accessors.
Object and Collection Initializers
Object initializers let us assign values to any accessible fields or properties of an object at creation time without having to invoke a constructor followed by lines of assignment statements.
Consider the class “baabtraStudent” again
Suppose if we want to create 3 object instances of this class, we will have to write the following code,
This needs a lot of code to be written to initialize objects.
C# offers another method of object initializing as shown in the following code
Which saves a lot of coding and time for the developers.
A collection object of the “baabtrStudent” class (List<baabtraStudent>) can also be initialized in the same way as in the following code. This eliminates creating and adding new objects to the collection one by one.
Extension Methods
Extension methods help us to add new methods to existing types without modifying the original code, inheriting or aggregating .
Consider a simple class called “mathOperations” which is having only an addition method, which takes two numbers as arguments and returns the added value as result.
Suppose this class is added as a compiled dll to our application and the source code is no longer available to edit and add other methods.
We can create an instance of this class in our application and perform an add function and display the result as in the following code
When we put a dot to the right of the mathOperations variable the “add” method is populated in the intelliscence
And the program runs smoothly
Now if we want to find the difference between two numbers, there is no subtract method available in the “mathOperations” class. So to add a subtract method we can go for 3 options
add a subtract method in the “mathOperations” class – this is not possible as mathOperations is a third party dll and we don’t have the source code for it.
Through aggregation - Create a wrapper class around the math operations class and add the subtract method as shown in the following example
And access the method as shown in the following code
But now as you can see the add method can only be accessed through a mathOperations field of wrapperMathOperations class and is not directly accessible from the wrapperMathOperationsClass.
The third method is to inherit the mathOperations class and add the subtract method
In any of the three methods the complexity of the class structure is increased.
The correct solution to such a scenario is an extnesion method “subtract” for the mathOperations type which can be created in the following way,
Now the method “add” and “subtract” (as an extention method, see the blue arrow right to the pink block) appears in the intelliscense block for an object instance of the mathOperations class as shown in the following fig.
Summary extension methods enable us to add methods to a datatype without changing
the code for the datatype or creating a derived type.
An extension method must be a static method inside a static class
they can be called on the object instance in the same way as we call any other defined methods in the object class
Anonymous Methods & Lambda Expressions
Anonymous methods provide a technique to pass a code block as a delegate parameter. Anonymous methods are basically methods without a name, just the body.
We need not specify the return type in an anonymous method; it is inferred from the return statement inside the method body.
Anonymous methods are declared with the creation of the delegate instance, with a delegate keyword. For example
The code block Console.WriteLine("Anonymous Method: {0}", x); is the body of the anonymous method.
The delegate could be called both with anonymous methods as well as named methods in the same way, i.e., by passing the method parameters to the delegate object.
By using anonymous methods, we reduce the coding overhead in instantiating delegates because you do not have to create a separate named method.
The scope of the parameters of an anonymous method is the anonymous-method-block.
It is an error to have a jump statement, such as goto, break, or continue, inside the anonymous method block if the target is outside the block. It is also an error to have a jump statement, such as goto, break, or continue, outside the anonymous method block if the target is inside the block.
Lambda expressionsLambda expressions are similar to anonymous methods with the difference that in lambda expressions we don’t have to use the “delegate” keyword and the input parameter type explicitly.
Lamda expressions are more easy to write than anonymous methods because they need much lesser amount of coding and they are syntactically simpler.
Lambda expressions are particularly helpful in writing LINQ query expressions.
In an anonymous method the inout parameters canbe completely omitted if they are not used inside the method block but in case of a lambda expression this is not possible.
Most of the time lambda expressions supersede anonymous methods unless the input parameters to the method has to be omitted which is not possible in lambda expressions
ExamplesThe examples below demonstrates the same functionality implemented with anonymous method and lambda expression
Anonymous method
ExamplesLambda expression
Automatic type inference
The var keyword in C# allows the compiler to infer the type of a variable implicitly.
A var can be set to any type like, string, int, double etc.
The var can be used to access a variable based on an anonymous class.
var is only allowed for local variables
var is also strongly typed, but by the compiler. For example, The following two declarations of i are functionally equivalent:
A variable of type var cannot be initialized to null
After the initial assignment the type of the variable is fixed
Follow us @ twitter.com/baabtra
Like us @ facebook.com/baabtra
Subscribe to us @ youtube.com/baabtra
Become a follower @ slideshare.net/BaabtraMentoringPartner
Connect to us @ in.linkedin.com/in/baabtra
Thanks in advance.
www.baabtra.com | www.massbaab.com |www.baabte.com
Contact Us
Emarald Mall (Big Bazar Building)Mavoor Road, Kozhikode,Kerala, India.Ph: + 91 – 495 40 25 550
NC Complex, Near Bus StandMukkam, Kozhikode,Kerala, India.Ph: + 91 – 495 40 25 550
Cafit Square,Hilite Business Park,Near Pantheerankavu,Kozhikode
Start up VillageEranakulam,Kerala, India.
Email: info@baabtra.com
top related