New features in C# language

Auto-Implemented Properties

Suppose this is our Person class with two properties First Name and Last Name.

public class Person
    {
        private string firstName;
        private string lastName;
        public string FirstName
        {
            get
            {
                return firstName;
            }
            set
            {
                firstName= value;
            }
        }  
        public string LastName
        {
            get
            {
                return lastName ;
            }
            set
            {
                lastName = value;
            }

        }
    }

 

Here we are not putting any extra logic while using get and set blocks for the properties, so the above code could be written as following using Auto-Implemented Properties.

 public class Person
    {
        public string FirstName { get;set;}
        public string LastName { get; set; }

    }

 

Things to remember :-

Both get and set accessor are required.

To make it read only we can declare set accessor as private

 public string LastName { get; private set; }
 
 

Object Initializers 

To initialize our Person object normally we would be writing the following code

  Person person = new Person();
  person.FirstName = “Nishant”;
  person.LastName = “Rana”;

 

However now we could do this in much simpler manner

Person person = new Person() { FirstName = “Nishant”, LastName = “Rana” };

 

Using Object initializers we can assign values to any accessible fields or properties of an object at creation time without having to explicitly invoke a constructor.

 

 

 

Extension Methods

Using Extension methods we can add methods to existing types without creating a new derived type, recompiling or modifying the original type.

Suppose this is how we have defined our Person class with one method named GetFirstName.

public class Person
    {
        public string FirstName { get;set;}
        public string LastName { get; set; }

        public string GetFirstName()
        {
            return FirstName;
        }
    }

 

Now we will add method to this existing Person Type named GetLastName

 public static class PersonExtension
    {
        public static string GetLastName(this Person p)
        {
            return p.LastName;
        }
    }

Here we need to follow these rules

  • We need to declare our class as static.
  • We need to define the method as static and the first parameter is preceded by this keyword and specifies which type the method operates on.

Now the code that calls both these methods. GetLastName function would be called as if it was an instance method and not an static one.

   Person person = new Person() { FirstName = “Nishant”, LastName = “Rana” };
   string firstName = person.GetFirstName();
   string lastName = person.GetLastName();
           
 
 

Collection Initializers

Here instead of writing the following code to intialize the collection

   List<Person> lstPerson = new List<Person>();
   Person person1 = new Person() { FirstName = “Nishant”, LastName = “Rana” };
   Person person2 = new Person() { FirstName = “Ashutosh”, LastName = “Pandey” };
            lstPerson.Add(person1);
            lstPerson.Add(person2);
we could use the following syntax, without making use of add method
 
List<Person> lstPerson=new List<Person>()
            { 
                {new Person { FirstName=“Nishant”, LastName=“Rana”}},
                {new Person {FirstName =“Ashutosh”, LastName=“Pandey”}}                
            };

 

 

Implicitly type local variables

Now we can declare variables using var keyword (implicitly) without explicitly defining their type.

 string FullName = “Nishant Rana”;
or
var FullName = “Nishant Rana”;
 
 
var myStringArray = new[] { “a”, “b”, “c” };
 
The above two lines of code are equivalent.
Here compiler infer the type of variable from the expression on the right side. It could be built-in type, user-defined type, anonymous type or any other type defined in .NET framework.
 
 

Anonymous Types

Anonymous types are class types that contain one or more public read only properties.

var v = new { FirstName = “Nishant”, LastName = “Rana” };

The above line of code creates a anonymous class having two public read only properties named FirstName and LastName.

Things to remember :-

  • The compiler gives name to the anonymous types but our application won’t be able to access it.
  • It cannot be cast to any type except “Object’”.

Anonymous methods and Lambda expressions

Suppose this is our simple delegate

 public delegate void MySimpleDelegate();

 

And this is the function which it points to

  public void MySimpleFunction()
        {
            Response.Write(“Simple function”);
        }

 

And this is how we would be using the delegate

  MySimpleDelegate mySimpleDelegate = MySimpleFunction;
   mySimpleDelegate();

 

Now here instead of defining the MySimpleFunction separately we can make use of anonymous methods

  MySimpleDelegate mySimpleDelegate = delegate
            {
                Response.Write(“Simple function”);
            };
mySimpleDelegate();

 

Infact we can also use lambda expression over here

MySimpleDelegate mySimpleDelegate = () => Response.Write(“Simple function”); 
mySimpleDelegate();
 
 
Here       ()           –>  no input parameter
and        =>          –> lamda operator
 
 
 
Optional parameters
 

We can declare an optional parameter by specifying default value as a part of declaration

public void GetTotal(int a = 0, int b = 0)
        {
            MessageBox.Show((a + b).ToString());
        }

We can call the above method in any of the following way

 
            GetTotal(1, 1);
            GetTotal(1);
            GetTotal();

 

Named Arguements

Name the arguments to be passed
            GetTotal(a: 1, b: 2);
            GetTotal(b:2, a: 1);
This will throw error named argument must appear after fixed arugments have been specified
 
           GetTotal(a:1, 2);

Dynamic Type

New dynamic type that allows us to do things that are resolved during run time.

         dynamic dString = GetName(“a”,”b”);
         dynamic dInt = 12;

 

Bye.


Author: Nishant Rana

I love working in and sharing everything about Microsoft.NET technology !

Share your thoughts

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s