Download presentation
Presentation is loading. Please wait.
1
C# 5 and 6 Tips and Tricks Telerik Academy Plus http://academy.telerik.com C# Tips and Tricks
2
1. C# 6 – History and Important New Features 2. Syntactic Sugar and Language Features 3. Traps 4. Useful.NET Classes and Methods Demos: github.com/NikolayIT/CSharp-Tips-and-Tricks github.com/NikolayIT/CSharp-Tips-and-Tricks 2
3
https://github.com/NikolayIT/CSharp-6-New-Features
4
4 C# 1.0 VS 2002.NET 1.0 Managed Code C# 2.0 VS 2005.NET 2.0 Generics Generics ReflectionReflection Anonymous Methods Partial Class Nullable Types C# 3.0 VS 2008.NET 3.5 Lambda Expression LINQLINQ Anonymous Types Extension Methods Implicit Type (var) C# 4.0 VS 2010.NET 4.0 dynamicdynamic Named Arguments Optional Parameters More COM Support C# 5.0 VS 2012.NET 4.5 Async / Await Caller Information C# 6.0 VS 2015.NET 4.6 A lot of new syntax features….NET Compiler Platform (Roslyn)
5
You can add an initializer to an auto-property, just as you can to a field: The initializer directly initializes the backing field Just like field initializers, auto-property initializers cannot reference "this" 5 public class Person { public string FirstName { get; set; } = "Nikolay"; public string FirstName { get; set; } = "Nikolay"; public string LastName { get; set; } = "Kostov"; public string LastName { get; set; } = "Kostov";} this. k__BackingField = "Nikolay";
6
Auto-properties can now be declared without a setter: The backing field of a getter-only auto- property is implicitly declared as read-only: It can be assigned to via property initializer In future releases it will be possible to assign it in the declaring type’s constructor body public string FirstName { get; } = "Nikolay";.field private initonly string ' k__BackingField' 6
7
Methods as well as user-defined operators and conversions can be given an expression body by use of the “lambda arrow”: The effect is exactly the same as if the methods had had a block body with a single return statement For void returning methods - expression following the arrow must be a statement 7 public object Clone() => new Point(this.X, this.Y); public static Complex operator +(Complex a, Complex b) => a.Add(b);
8
Expression bodies can be used to write getter- only properties and indexers where the body of the getter is given by the expression body Note that there is no get keyword It is implied by the use of the expression body syntax 8 public Person this[string name] => this.Children.FirstOrDefault( x => x.Name.Contains(name)); this.Children.FirstOrDefault( x => x.Name.Contains(name)); public string Name => FirstName + " " + LastName;
9
Occasionally you need to provide a string that names some program element When throwing ArgumentNullException When raising a PropertyChanged event When selecting controller name in MVC nameof() = Compiler checks, navigation, easy for renaming (refactoring) 9 if (x == null) throw new ArgumentNullException(nameof(x)); @Html.ActionLink("Sign up",nameof(UserController),"SignUp")
10
Syntactic sugar used to construct strings Template strings containing expressions Creates a string by replacing the contained expressions with their ToString represenations As a result strings are easier to read/understand Curly brackets are escaped by two brackets 10 // C# 5 var str = string.Format( "Name = {0}, hours = {1:hh}", name, hours); "Name = {0}, hours = {1:hh}", name, hours); // C# 6 var str = $"Name = {name}, hours = {hours:hh}"; Console.WriteLine($"{{name}}"); // Prints {name}
11
The null-coalescing operator (??) returns: The left-hand operand if the operand is not null Otherwise it returns the right hand operand Write: Instead of: It also can be chained: 11 var pageTitle = (title != null) ? title : "Default Title"; var pageTitle = title ?? "Default Title"; return firstValue ?? secondValue ?? thirdValue;
12
Lets you access members and elements only when the receiver is not-null Providing a null result otherwise Can be used together with the null coalescing operator ??: Can also be chained 12 int? length = customers?.Length; //null if customers is null Customer first = customers?[0]; //null if customers is null PropertyChanged?.Invoke(e) //PropertyChanged is an event int length = customers?.Length ?? 0; // 0 if customers null int? first = customers?[0].Orders?.Count();
14
A generic type parameter can be one of: Invariant (default) – meaning the generic type parameter cannot be changed Contravariant – the generic type parameter can change from a class to a class derived from it In C# we indicate this with the in keyword Can appear only in input positions (method’s argument) Covariant – the generic type argument can change from a class to one of its base classes In C# we indicate this with the out keyword Can appear only in output positions (method’s return type) 14
15
?: - ternary operator + chaining Partials classes and methods? Short initializing of arrays = { 1, 2, 3 } extern alias for resolving namespace conflicts params for arbitrary number of parameters Custom Indexers public string this[string ind] Omit generic type when call method X (y) Multicast delegates (+=, -=) + Equality of delegates @keyword for variable and class naming public static explicit operator MyEntity Hide Interface Implementation 15
17
System.Object is the base class for all types System.ValueType is the base class for all value types (struct & enum) 17
18
All structs derive from the same ValueType class The ValueType.Equals(Object) method overrides Object.Equals(Object) and provides the default implementation of value equality By default when comparing structs with Equals() If none of the fields of the current instance are reference types => byte-by-byte comparison Otherwise it uses reflection to compare the corresponding fields (~20 times slower!) We can improve the performance of structs by comparing them with overridden Equals 18
19
Calling virtual methods in a constructor is a bad idea When initializing a type in C# constructors are invoked top-down First the top base constructor Then down to the derived constructors through the inheritance But virtual methods are invoked bottom-up First the most derived overridden method Then up to all base virtual methods For this reason, if you call virtual methods in constructor you may have unexpected behavior from your classes 19
20
Hash code is used in various hash-based collections (HashSet, Dictionary ) In C# an overridden method named GetHashCode provides the hash code generation for a particular type If you generate custom hash code for a type, try to use read-only properties for it Non-read-only properties may change the hash code run-time and collections will not be notified for the change Thus the internal structure and algorithms of the collection will not be able to retrieve and use the modified instance 20
21
The.NET runtime employs a very smart garbage collector to clean up objects that are no longer used This doesn't mean that you'll never lose track of memory Not removing event listeners Any event listener that is created with an anonymous method or lambda expression that references an outside object will keep those objects alive Keeping database connections or result sets open when they are not used Call to functions using P/Invoke which allocate memory which you then never release 21
23
The System.IO.FileSystemWatcher class makes it possible to execute code when certain files or directories are created, modified, or deleted It listens to the file system change notifications and raises events Few things to consider: Sometimes events may be raised multiple times Instance members are not thread safe The watcher will continue listening until the EnableRaisingEvents is set to False More: http://weblogs.asp.net/ashben/31773 http://weblogs.asp.net/ashben/31773 23
24
Concat() – concatenates sequences Order of which sequence comes first matters Union() – c Union() – c oncatenate sequences without duplicates Duplicates are determined by using an IEqualityComparer or Equals() + GetHashCode() 24 PrintList(firstList.Concat(secondList)); // apples,bananas,cherries,durian,durian,eggplant,apples PrintList(firstList.Union(secondList)); // apples, bananas, cherries, durian, eggplant PrintList(firstList.Union(secondList,new LengthComparer())); // apples, bananas, cherries firstList = { "apples", "bananas", "cherries", "durian" }; secondList = { "durian", "eggplant", "apples" }
25
Intersect() – subset of each collection that is found in both collections (i.e. common elements) Except() – subtracts elements from a collection (i.e. first collection minus second one) Both Intersect() and Except() depend on Equals() + GetHashCode() or IEqualityComparer Both Intersect() and Except() depend on Equals() + GetHashCode() or IEqualityComparer 25 PrintList(firstList.Intersect(secondList)); // apples, durian PrintList(firstList.Except(secondList)); // bananas, cherries firstList = { "apples", "bananas", "cherries", "durian" }; secondList = { "durian", "eggplant", "apples" }
26
Zip() – for each elements: combines element from the first sequence an with element from the second sequence using result selector function Aggregate() – Applies an accumulator function over a sequence Built-in: Count, Min, Max, Sum and Average 26 PrintList(listOfNumbers.Zip(firstList, Tuple.Create)); // (1, apples), (2, bananas), (3, cherries), (4, durian) Console.WriteLine(firstList.Aggregate((s, c) => s + c))); // applesbananascherriesdurian listOfNumbers = Enumerable.Range(1, 4); firstList = { "apples", "bananas", "cherries", "durian" };
27
string.IsNullOrEmpty / IsNullOrWhiteSpace Convert.ChangeType() DateTime.ToLocalTime() Char.GetUnicodeCategory() Object.ReferenceEquals() 10.ToString("(+)#.##;(-)#.##;(nothing)") Process.Start() Array.AsReadOnly() Array.Resize() Array.CopyTo() int.Parse("(24)",NumberStyles.Allow…) DateTime.ParseExact() BitConverter.GetBytes() Custom format provider (IFormatProvider) 27
28
Path.Combine() / Path.ChangeExtension()… Configuration files new Lazy () -> lazy initialization char.GetNumericValue( ⅔ ) = 0.6666… ZipFile.CreateFromDirectory GZipStream / DeflateStream Uri/UriBuilder class (relative, absolute, parts) Task.Delay() Joins Debugging [DebuggerStepThrough] + Just My Code [DebuggerTypeProxy(typeof(SomeTypeProxy))] 28
29
форум програмиране, форум уеб дизайн курсове и уроци по програмиране, уеб дизайн – безплатно програмиране за деца – безплатни курсове и уроци безплатен SEO курс - оптимизация за търсачки уроци по уеб дизайн, HTML, CSS, JavaScript, Photoshop уроци по програмиране и уеб дизайн за ученици ASP.NET MVC курс – HTML, SQL, C#,.NET, ASP.NET MVC безплатен курс "Разработка на софтуер в cloud среда" BG Coder - онлайн състезателна система - online judge курсове и уроци по програмиране, книги – безплатно от Наков безплатен курс "Качествен програмен код" алго академия – състезателно програмиране, състезания ASP.NET курс - уеб програмиране, бази данни, C#,.NET, ASP.NET курсове и уроци по програмиране – Телерик академия курс мобилни приложения с iPhone, Android, WP7, PhoneGap free C# book, безплатна книга C#, книга Java, книга C# Николай Костов - блог за програмиране форум програмиране, форум уеб дизайн курсове и уроци по програмиране, уеб дизайн – безплатно програмиране за деца – безплатни курсове и уроци безплатен SEO курс - оптимизация за търсачки уроци по уеб дизайн, HTML, CSS, JavaScript, Photoshop уроци по програмиране и уеб дизайн за ученици ASP.NET MVC курс – HTML, SQL, C#,.NET, ASP.NET MVC безплатен курс "Разработка на софтуер в cloud среда" BG Coder - онлайн състезателна система - online judge курсове и уроци по програмиране, книги – безплатно от Наков безплатен курс "Качествен програмен код" алго академия – състезателно програмиране, състезания ASP.NET курс - уеб програмиране, бази данни, C#,.NET, ASP.NET курсове и уроци по програмиране – Телерик академия курс мобилни приложения с iPhone, Android, WP7, PhoneGap free C# book, безплатна книга C#, книга Java, книга C# Николай Костов - блог за програмиране http://academy.telerik.com
30
C# Programming @ Telerik Academy csharpfundamentals.telerik.com csharpfundamentals.telerik.com Telerik Software Academy academy.telerik.com academy.telerik.com Telerik Academy @ Facebook facebook.com/TelerikAcademy facebook.com/TelerikAcademy Telerik Software Academy Forums forums.academy.telerik.com forums.academy.telerik.com 30
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.