Here are some more of the essential new features in C# 6.0
5. Importing Static classes via USING keyword
Static in C#:
Static is a compiler reserved keyword in C#, which can be applied to any member of a class i.e. well Fields, methods, classes, Properties, Events or to a class itself as well.
There will be only one copy of a member variable declared as static. Each object has its own copy of instance variables whereas static variables are shared across objects.
Lifetime:
Static variables are allocated when type containing the static variables is loaded in memory and are unallocated when the class is removed from memory.
Storage:
Static variables, Static Methods as well as normal methods are stored in a special area of heap called “PermGen”. PermGen stores only primitive values of static variables, if the static variable is a reference type than the reference variable will be in PermGen whereas the actual object will be allocated in Heap.
Usage:
System.Console.WriteLine(“Hello Static”);C# 6.0
There is short and concise way of calling static methods
using System; using System.Console; //Importing System.Console will import all static methods in //current namespace namespace CSharp6 { class MyClass { public void Hello() { WriteLine("Hello Static"); } } }6.Async in Catch and Finally Blocks
The most common programming practice is to catch exceptions and log them. Logging involves IO since we usually log into files or databases. IO operations are usually expensive in terms of performance which means that in a serviced kind of environment, the end-user who is waiting for a response is actually being kept waiting for logging messages as well.
Logging and Auditing are cross-cutting concerns, which means that they are not specific to a particular layer in application architecture but used throughout. To make performant systems we should write code in a way that returns a response to the user as soon as possible. In the past to improve performance we used to write in in-memory buffers and later dump that buffer into files or databases. This reduces the IO but poses challenges like if the program crashed we might lose onto important information which could have helped in troubleshooting.
C# 5 brings Async and Await keywords to the table. Async and Await are code markers that free the thread if it’s waiting for some IO operation. This improves performance in web applications where threads are utilized from ThreadPool. Since as soon as the compiler encounters an await keyword, it marks the rest of the method as continuation or callback and returns the caller thread to pool. Once free this thread can cater to other requests and when IO operation completes, the marked callback is executed by a free thread from ThreadPool.
In C# 6.0 we can write the logging and auditing code using async and await
public async void ExceptionFilters() { try { //Do Something } catch (Exception ex) if (!ex.GetType().Equals(typeof(ArithmeticException))) { await Task.Run(() => { var writer = new StreamWriter("c:\\temp\\logtester.log", true); writer.Write("Some value to log"); }); //More code } }7.Name Of Expression
Many times in code we need to write the name of class member. Usually while throwing validation exceptions from server or firing PropertyChanged events in case of 2 way bindings. C# 6.0 introduces nameOf expression
e.g.
public void OldWay(string firstName , string lastName) { if (firstName != null) throw new Exception(string.Format("{0} is required", "firstName")); if (lastName != null) throw new Exception(string.Format("{0} is required", "lastName")); } public void NewWay(string firstName, string lastName) { if (firstName != null) throw new Exception(string.Format("{0} is required", nameof(firstName))); if (lastName != null) throw new Exception(string.Format("{0} is required", nameof(lastName))); }More Example where this can be handy:
class Person : INotifyPropertyChanged { int _personId; public int PersonId { get { return _personId; } set { _personId = value; //Old way // OnPropertyChanged("PersonId"); //New OnPropertyChanged(nameof(PersonId)); } } public event PropertyChangedEventHandler PropertyChanged; public void OnPropertyChanged(string propertyName) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } }Using this keywords helps cleaning up code by removing literals in code.
Declaring out parameter during method call
Time and again micsrosoft has come up with syntaxes that have been used for brevity. One handy addition is removing the need for declaring out parmeter before actually using it.
public bool TryParseInt(string value) { if (int.TryParse(value, out int parsedvalue)) { return true; } return false; }8.String Interpolation
Prior to C# 6.0 String concatenation sometimes became challenging in older versions of c#, primarily since we need to write numeric placeholders and than variables in same order. Consider below example
string firstName = "Abhishek"; string lastName = "Tomer"; string title = "Mr."; string fullName = string.Format("{0} {1} {2}", title, firstName, lastName);In above example, placeholders i.e. {0} ,{1} and {2} and kinda magic numbers. Also the order in which we are passing the parameters becomes very important so chance of mistakes are more. We should avoid magic numbers in code since they hamper readability and code understanding.
A handy addition in C# 6.0 is named placeholders which also removes the reliance on parameter ordering while creating strings e.g. Above code can be rewritten in C# 6.0 as :
string firstName = "Abhishek"; string lastName = "Tomer"; string title = "Mr."; string fullName = string.Format("\{title} \{firstName} \{lastName}"); Console.WriteLine("\{title} \{firstName} \{lastName}");As you can see syntax is self-explanatory. Don’t forget to add leading “\” with named placeholders else it will be treated as a string and output as is.
9.Exception Filters
Again this is something which was supported in VB but have been introduced into c# as well.
public void ExceptionFilters() { try { //Do Something } catch (Exception ex) if (!ex.GetType().Equals(typeof(ArithmeticException))) { //Do something } }As you can see, we have created a filter to handle everything except for ArithmeticException
10.Null conditional operator
I have seen in recent past Microsoft has brought back lot of legacy VB stuff into C#. If you remember VB provides with clause , this features bring back memory of that.
Dim theCustomer As New Customer With theCustomer .Name = "Coho Vineyard" .URL = "http://www.cohovineyard.com/" .City = "Redmond" End WithExplanation
Lets say we have a Customer class with a property of type CustomerDetails as below
public class Customer { public CustomerDetails CustomerDetails { get; set; } } public class CustomerDetails { public string CustomerName { get; set; } }Many a times we need to write a code to set CustomerName property as below with proper null checks.
//Prior to C# 6 private void SetCustomerName(Customer customer) { if ( customer !=null && customer.CustomerDetails!=null) customer.CustomerDetails.CustomerName= "Abhishek"; } //With C# 6.0 private void SetCustomerName6(Customer customer) { customer?.CustomerDetails?.CustomerName ?? "Abhishek"; }So, Guys these are all the New features of C# 6.0.
I Hope in this post I have covered all the points of New Features in C# 6.0.
Please share this post with your friends and colleagues.
For any queries please post a comment below.
Happy Coding 😉
0 comments:
Post a Comment
If you like this website, please share with your friends on Facebook, Twitter, LinkedIn.