Introduction:
The
major aim of C# 4.0 is dynamic programming.More importantly objects are dynamic
and
their behaviours , properties are not accessed by static types.
Sample Example:
- objects from dynamic programming languages
- ordinary .NET types accessed through reflection
- objects with changing structure, such as HTML DOM script objects
- data readers and other user defined dynamic object
New Features are..
Dynamic type-
In C# 4.0 a new keyword is
introduced:" dynamic " and it's used to tell the compiler that the
object is defined at runtime. A dynamic object is assumed to support any
operation at compile time.
dynamic objCust =GetCustomer();
objCust.FirstName ="Venkat" ;
objCust.LastName ="Vijay" ;
objCust.CalculateSalary();
In
this case, the variable objCust is declared dynamic, in this way , the C#
compiler that the type of Customer is not known until run time, but it can
dispatch messages to it. For example, at run time, the compiler discovers the
properties to be called (FirstName and LastName) and the method
CalculatedSalary which is resolved only on execution. This way, the dynamic run
time receives information about the call such as its name and parameters. With
this information, application can call the right function (in Iron-Python). If
the method is not defined, then an exception of type RuntimeBinderException is
thrown.
Named and optional arguments
Another
new feature is named and optional arguments/parameters. Optional parameters
allow giving a method parameter a default value, so you don't have to specify
it every time you can call the method directly.
using System;
using System.Collection.Generic ;
using System.Linq ;
using System.Text ;
namespace CSharpNewFeatures
{
class Demo
{
public static void
MyMethod(int age, String name="Vishnu" , double salary=20000)
{ }
static void Main(string[] args)
{
MyMethod(23);
MyMethod(23,"Hello");
MyMethod(23,"Hi",20000);
MyMethod(23
,salary:20000);
}
}
}
Covariance
and Contravariance
Another
new feature is the use of covariance and contravariance of generics. Covariance
allows casting of generic types to the base types, for example, IEnumerable<A>
will be implicitly convertible an IEnumerable<B>
using
System;
using System.Collection.Generic ;
using System.Linq ;
using System.Text ;
namespace CSharpNewFeatures
{
class Demo
{
static void Main(string[] args)
{
IList<string> arrNames=new List<string>();//here we have a list of
string.
IEnumerable<object>objects =arrNames ;//here converted to an Enumerable
collection.
}
}
}
No comments:
Post a Comment