Transcripts
1. C# language features: Let me ask you a question. Would you like to become a C sharp experts? I mean, the C sharp language is pretty cool. But if you learn the language at school or in the course, then you're only the only learned the basics. You don't really learned the power features of the language. So what I I'm trying to do in this course is teach you a couple off Really cool advanced features off the C sharp language. So, for example, we're going to take a look at extension methods. We're gonna take a look at the yield return statements. You have any idea what you'll return does and how you're supposed to use it? I'll teach you. We're going to take a look at link expressions. We're gonna take a look at the null conditional operators. We're gonna take a look at some advanced features that were introduced in C sharp version six. So, for example, we're gonna take a look at out all property initialize hours, so I'll tell properties that you initialize. We're going to take a look at declaration bodies, expressions. So expressions written out as a London function that you used to initialize a method so really cool stuff. So by the end of this course, you will be up to speed on roughly 15 advanced See Shoaib language features that you can use to improve your own sees or c sharp source calls. It will help you write less coat because a lot of these features automates away a lot off handwritten code that you have to write in the past on this knowledge will help you become a better developer. So are you interested in becoming a C sharp experts? Then this is the course for you. So I created this course for junior meteor or senior developers. Doesn't matter what level you have, who want to take their knowledge off the C sharp language to the next level on this knowledge is going to be really useful to you in your career when your next promotion is you or when you're applying for a job. So thank you for listening on. I hope I'll be seeing you in the course
2. Course introduction: Hi. Welcome to this course. Spice up your C sharp coat with advanced language features. In this course, I will teach you a list off Very cool and advanced C. Sharp language features. So here's the scene about C. Sharp. Microsoft's released this language in 2002 more than 14 years ago. At the time, C Sharp was little more than a variant off Java with a slightly more powerful feature sets . But over the years, the language has evolved enormously and matures into its current incarnation. At version six today, C Sharp is both strongly ants, dynamically typed objects, aunts, component oriented, generic imperative, declarative on functional programming language That's quite a mouthful. Andi. It drives the point home that C Sharp is a multi paradigm programming language. It contains features from more than one programming paradigm. Here's a short list. C Sharp is object oriented. C. Sharp is also declarative because it supports attributes. But C Sharp is also functional because it supports link on Lunda expressions on D. C. Sharp is dynamically types because it supports dynamic variables. C Sharp is packed with features on. It's quite normal to have words with the language for years without ever touching a specific feature. In my case, I can honestly say that I have never used the dynamic keywords in any off my projects. Despite my decades long experience with C Sharp on. This is exactly what gave me the inspiration to make this course. Wouldn't it be great if we had all the cool and useful features off C sharp groups together in one handy course? And so in this course, I will teach you 10. Very cool, lesser known on advanced power features off the seashore language. I will also give you a nice overview off the new features that Microsoft introduced Inversion six off the C sharp language. I will start each section with an overview off what you will learn, and I will end the section with a recap on the short quiz that you can use to test your knowledge. If you fail, the quiz town to worry about is just re read the corresponding lecture on, then try again. And if anything is unclear to you, feel free to reach outs than contact me. I'm happy to answer any questions you might have. By the end of the course, you will have a solid grasp off many advanced see short language features, and he will be entirely up to speed on all the new features that Microsoft introduced Inversion six. Okay, so now you might be wondering, Who is this guy on? What does he know about C Sharp? Well, hi, my name is Mark Finegar. Let me tell you a bit about my background. I studied physics at the University of Utrecht in the Netherlands. After graduation, I started my career at a small I T company called Vision. I had a great time and I worked my way up to project manager, and I became close friends with the company art director. In the year two thousands, we decided to team up and form our own company called Design State. So here's a group photo from three years later. We have grown to 12 people in just three years, and we worked on all kinds of cool projects. For example, here is a video phone that we build for Dutch Internet millionaire, echoed Vincent. We programmed the device in C sharp coat that ran on the dot net compacts. Rain work on a compact smartphone. Sadly, design State went bust in 2003 but I continued to work on cool projects. Here is a supermarket shelf I worked on. The cool thing about this shelf is that it has built in, or if I d antennas so it could sends. When products were placed on his, I programmed the whole thing in C Sharp and a Speedo. Next, in 2007 I got together again with my former business partner, and we formed a new company called First Focus. So here's another cool projects we did together. This is an e commerce website. It's an egg, a Speedo net. Wet forms projects on it runs on a cloud off Lena servers. We went live a few years ago on we achieve spectacular results. The site contains 100,000 products in over 7000 categories. It has life facets. Navigation on data renders pages in a fraction of a second. So there you have it. I've been using C sharp for at least 14 years. I have worked on some very cool projects and I love to share my C sharp experience with you . My I T career is now over 20 years old. In that time, I started to tech companies. I mean a CDO four times, and I've taught in classrooms for five years, and I've worked on many, many great projects that Hughes C Sharp in somewhat unconventional environments. Now I've reached the point where I would like to share everything that affluent with you. Making online courses is a lot of fun, and I really enjoy being a virtual teacher. I love the idea of connecting with people all over the world, so thank you again for enrolling in this course. Let's get started.
3. The null coalescing operator: Okay, let's get started with our list off. Cool C Sharp language features. The first feature I'd like to talk about is the so called no coalescing operator on this little operator is really useful when we're dealing with cold like this. So I have a string variable here called Name I assigned some kind of valiant with valuable . But if that value is actually no, then I want the name variable to hold an empty string instead. This is useful if the remaining cult uses the name variable without checking for no values every time. To be fair, there is nothing wrong with checking for no values in lots of places in your code. But sometimes the number off checks you need to do gets out of hand. Aunt Innocently more convenient to work with an empty string instead. So we have this snippet of cold, which tends to pop up a lot in C sharp projects. One way to simplify the colds is by using the turn. Every operator you've probably seen this operator many times eats the one with the question . Work on the colon. If I re factor these snippets to use the tannery operator, I get the following results. I must have typed cold like this 1000 times in my projects. The turn Arriaga aerator returns either the value or an empty string if the value is no so exactly the same behavior that's before. But now we have lost the S statements on alert code is nicely on the same line, but you can simplify this cult even further. The no coalescing operator has the null check built in on so you can write the code simply like this. Behind the scenes, it's still the same coat the check for no. Then return either the value or an empty string. But with this operator, I can write the code out in a super compact way. So here, on a number of cool things you can do with this operator. First of all, let's take a look at notable types. I can sit up a snippet of code like this with a notable interviewing gable. So I have a knowable interview Variable called number, which I said to know this is perfectly valid because it's unknowable integer it can't be No , But now look at the second line there I declare a normal interview available, called results on. I assign the number to it. So what happens? A normal integer cannot contain no values. So the compiler will refuse to compile this cult. Check this out. See, that didn't work. To get the colds compiling, I need to do with typecast like this. I will re compartment. I see no errors. So now I can run the program. Here we go on. You see, I get an invalid operation exception that makes perfect sense because I'm trying to stuff no value into a normal integer which is totally not allowed in c sharp to prevent these kinds of runtime exceptions. The best thing you can do is stop using type pasts in this situation. Instead, use the no coalescing operator who like this. So now we're not compelled to cold. Everything is fine on when I run the colds. Here we go. See, I do not get an exception. So what's happening now is that I am still putting the notable interview into a non notable variable. But I am also specifying a default value off zero in case the gullible value is well, no, on this is the primary reason why this operator was introduced. The no coalescing operator makes it very easy to transition between knowable on non notable value types without having to use messy, null checks all over your coat. Another useful use case for the not coalescing operator is chaining defaults together. So here's how that works. Let's say I am signing a configuration parameter like this. Now imagine that I'm assigning a configuration value here, so value represents a configuration value on Let's say, there's also a local default on a global default for these value. So I want to assign this value. But if it's no, then I want to fall back to the local default. If that's no to, I want to fall back to the global default. So the cult to do this looks like this so you can clean this up using turn ary operators. But you have to nest him like this, so that's more compact, but not really very readable on. Yes, I've typed cold like this 1000 times in my projects to, but now watch this by using the no coalescing operator. The cult changes to this super compact source code. Andi. It's still completely readable, a huge improvement. I will show you what more application off the no coalescing operator. Let's say I have a property that returns a string builder with a large initial capacity. I want to initialize the string buffer at the last possible moments. This is called lazy loading. So many coves would look like this. The property returns. The string boulder buffer Aunt Initialize is it's on the flight. If the protected variable is no, this is classic lazy loading coat, something you use many times in C Short projects. Now let's simplify the cold with the null coalescing operator. Here's what the end result looks like. I'm running slightly ahead of myself here as the thing on the right off the operator is a declaration Expression on. We're going to see more of those later in this course. But for now, trust me that this cold either returns the buffer variable or if it is no, it initialize is available on the fly and then return to. So again we get the exact same behavior. But the source code is a lot more compact and easier to read. Okay, let me summarize this lecture. What have we learned? The known convalescing operator is written out in codes as expression one and then two question marks and then expression to the operator returns, especially one except when Expression one is no. In that case, it returns expression to. Instead, you can use the operator to easily transition between novel and non notable value types. You can also use the operator to return a sets off over rideable configuration values by chaining more than one operator together on. Finally, you can combine the operator with a declaration expression to implement lazy loading.
4. Soft typecasts: My next cool language feature has to do with typecasting. As I'm sure you know, a typecast converts an expression of a certain type into another type. Take a look at the following code snippets. I haven't objects array filled with different types of values. There's a dates, time value, a Boolean String and Inter juror of floats on a character. Then there's a loop that enumerates the array on attempts to cast each value to a stream on Display it on the console. Now it won't surprise you that this cold will fail. Only the Seward's array elements contains a stream, and the explicit cast will fail for all other elements. I will run the program to prove it. Here we go see an invalid cast exception for the first array elements. Justice, I predicted. Okay, so now let me make a few modifications. I'm going to change the coat to this Now the codes will no longer throw exceptions. I use the is operator to test if the element is a stream. If it is, I do the cast, which will now always succeed on display the value on the console. But if the element is not a string. I write a different message to the console much better, right? But we can improve this cult even further. The if statement is a very verbose on. We can re factor this into a much more compacts notation, just like we did with a no coalescing operator. Take a look at this. You see much better. I used the as operator to perform a soft cast. This is a type cast that goes ahead as normal if the types are compatible. But if the cast cannot be performed for whatever reason, instead, off throwing on invalid cast exception. The as operator simply returns no on in the right line statements. I use our friends than no coalescing operator to either output of the stream value or a message stating that that the value is not stream. This dramatically reduces Michael size, Yet everything is still very readable. There's one thing, though. You have to keep in mind. The softs cast cannot distinguish between a failed cast or a string with the value off. No. In both cases, the operator will return a no value. To distinguish between these two scenarios, you need to explicitly check for the null value like this. So which casts can be as operated? Perform well. Here's a list cast to reference types. Cost two notable types cast from and toe box values, but not user different castes. So check it out. Notable times are on the list. So let's say I want to modify the previous code snippets to display, all introduced in the Objects array. I can simply modify the calls like this. Easiest point the as operator now attempts to perform a soft cast toe unknowable integer. Even the cast succeeds. I'll haven't entered your value, but if it fails, I will have a null value in my knowledgeable inter. Sure variable in the right line statements I contest for no using these same old known coalescing operator. Just like with strings notice, however, that I now display miners. One. If the cast fails because I have to use a value that is compatible with the notable interview type I use on the other side off the coalescing operator. An important thing to remember is that the ants operator cannot perform user defined conversions. So if I have my own class set up like this, see here you have a name class with a string property called Value with its own getter and setter. And I have also added to implicit casts. The 1st 1 converts from String to Name, which creates a new name. Instance on initialize. Is it with a given stream on the second caste converts from name to string and simply returns the value property off the given name instance. So now what do you think happens when I run the following gold? I used the as operator to cast the object valuable toe a stream. The variable contains an instance off name, which has an implicit user defined cast to convert from name to string, so everything should work fine, right? Unfortunately, no, let me demonstrate by running the program. Here we go. See, I get the not a string message. The reason this doesn't work is because C Sharp evaluates implicit type casts during compile time on the as operator runs at runtime. So to fix this, you can either use a dynamic variable instead because dynamic variables are implicitly cast it at runtime or you can fall back to using an explicit cast on doing the type check manually, so you have to be careful with the as operator. It works great, but only for reference types. Novel times on boxed value types. It cannot handle user defined conversions at all. Okay, let me summarize what we have learned in this lecture. The as operator performs a soft typecast from one time to another. If the cast fails, the operator returns No. The as operator can cast a reference types notable types on boxed value types. The operator can be used with user defined conversions. You have to explicitly cast instead or use dynamic variables.
5. Auto properties: my next cool language Fisher has to do with properties. So let's take a look at a typical code snippets that sets up a property in C sharp. So this is a very simple class calls person that contains a single private Stringfield to hold the person's name. I also declared a public property for getting and setting the name. This is standards and border place C sharp coat that you've probably types and 1,000,000 times in your projects on. That brings me to the main problem. We need to type this fragment of code so many times that is really too much work. Wouldn't it be much better if we can compress all of these cards down to four lines? Well, without all properties, this is actually possible. Check this out. This is the exact same code. The C sharp compiler will compile this source codes on produce the exact same thing. A private field on a public property getter and setter. But now I have to type a lot less source codes to achieve the same results. So there you go on out. All property is a property where you simply type get on set or right after the property declaration. The C sharp component will then automatically create a private fields on fueling the cult for the getter and setter for you. So now you might be wondering, why use properties at all? Isn't it much simpler to use a field and make it public? Nigris see exactly the same number of source code lines, But now I don't need complicated compiler magic to automatically create ghettos and set us for me. Why would I need this feature? Well, there are important reasons to use properties over public feels. Let's say you start by introducing a public fields in your class. Then a couple of weeks later, you discover that you needs to lazy load this fields. So now you have to re factor of fields into a property on put the lazy loading codes in the getter. But now you've introduced a breaking change. The interface off your assembly has changed because what was once the field is now a property, any coat that calls your library will need to be re compiled. Another problem is that you'll needs new colts to reflect your assembly. Fields are accessible through reflection by using the get fields method But for properties , you'll need the gets properties methods. So any cold that uses a reflection like, say, serialization codes will need to be changed to take your re factoring into account on. If you're developing gooey codes, you will discover that decorative data binding only works on properties on not on fields. If you start out with a field and later discover you need toe data, binds the fields with the user interface control. Then you will have to reflect your coats to get it working. Finally, properties can be part of an interface, but feels cannot. So, for example, if you need to add a color property or a name property toe on interface, then go right ahead. There's no need to manually set up get on set methods. You can simply aren't in the property to the interface directly. I do this many times in my coat on. It's a great feature, so to sum up, properties are useful because you can later adds lazy loading or range check holds without re compiling clients cold. You can add lady loading or range check holds without changing reflection. Courts. You can only data Bynes against properties and properties could be part of interfaces. So now let me show you a cool thing you can do with auto properties. Let's say we want to set up on immutable objects, immutable objects or objects that you set up in the constructor and after that they can never be changed. This is very useful in multi threaded coat, where more than one threads can safely access the objects without having to worry that fields might unexpectedly change their value. So how would you manually set up immutable objects well like this? So I made the private field read only, which means it can only be sets in the class. Constructor. I've removed the property setter Andi added a constructor to initialize the field. This class can only be initialized with the constructor on once it's in Stan, she ate it. You can only get the name through the property now. I will simplify the cold by using auto properties. Here we go much shorter. Not that I specify a public getter. Andre Private Center. Yes, you can do that. You can use different visibilities for the getter and setter, A very cool feature. So now I initialize my property by calling the private center in the constructor on from Zen on the outside world can only access the public getter on not modify the value. However, there are two problems with this coat. The compiler creates a normal backing. Fields out, not read, only feels like we want, and the center is accessible from the entire person class. So the class itself can change the value so we do not get the multi threading benefits. The field is not read only on the person class can call the center at any time and change the field. A threat has no guarantee that another threat will not unexpectedly change the value off the name field. Microsoft realized that this is the problem and so they introduced a very nice feature in Seashore Up six. Now you can simply do this. Do you notice the change? The private sector is gone. The compiler is smart enough to realize that's a read. Only property can be backed with the private reads only field as to initialize the property . The compiler allows me to refer to the center in the constructor again. The compiler is smart and it will automatically refractor my code to refer to the private read only fields instead. On this truly creates an immutable object with a read only backing field that absolutely no property setter in the class. This class can now be safely used by more than one threat without needing any thread looking for synchronization. Okay, let me summarize what we have Lawrence in this lecture until properties are a feature where the C sharp compiler automatically creates the getter and setter cold on the backing fields . Decoration you right out of properties by following the property declaration with Get that set without specifying their implementation. Out of properties are useful because they allow future changes to getter and setter coat without breaking the assembly interface or requiring changes to reflection gold. You can also data bytes two properties and put them in interfaces. You can leave out the center to create an immutable class with a read only backing field on no center.
6. Three useful string methods: the string class has some very useful helper methods that are often overlooked on by using them. You can prevent your cards from becoming unnecessarily bloated. Take a look at the following snippet of code. I am writing a method to assemble a full name from a first name under the last name. This cold is perfectly fine. There's nothing wrong with it, but there is a more compact way to perform the no or empty string check. Let me modify the cold and show you chicken cells, so this is exactly the same code. The is no or empty method does the same checks behind the scenes. The only benefits of using this message is that it's less for bills, so there's less chance off a typing mistake, for example, typing on instead of or were not equal instead of equal. Okay, so that's a tiny benefits. But let's move on. There's a problem with his cold that is, that the first name might only contain spaces. The no or empty track will not cash. That's on. Therefore, I'll get a full name consisting off a bunch of space is followed by the last name to check against this condition. I need to change the cold as follows. You've probably seen this colds many times in your projects and rice. The standard way to check against a white space string is to trim its on, then check if we're left with zero string. But this solution has a major disadvantage. Strings are in variants, so every time the trim message is called, it is going toe allocates a new string on the heap. If the gets full name method is in a critical section of coat that is being called millions of times for seconds, then this solution is going to put a lot of pressure on the garbage collector by flooding the heat with strings. Now consider the following change I have replaced the if expression with a cool two is no or white space. So again, the code is less verbose, which reduces the chance of making a typo. But now I also have another advantage. The miss. It doesn't not allocate temporarily streams on the heap, that's all. Instead, it simply scans the stream on checks if it contains only whitespace characters. So now the cold is actually more efficient. It performs the same checks as before but avoids allocating a string on the each time it's called much better. Okay, so now I have my full name that I want to check it against unknown name, for example, my own. So I would have the following cult. Unfortunately, this won't work if the first name and last name variables used difference casing, for example, if they are all in uppercase. What I really need to do here is performed a case insensitive string comparison, so you often see cold like this. Unfortunately, this cold has the same disadvantage as using these training methods to check for an only white space string. The two upper methods creates a new string on the heap every time when it's called on in critical sections, this will flood the with lots of short lived, D referenced string audits. This will put a lot of unwanted pressure on the garbage collector, but we really want to do here is simply compare the two strings character by character without making any distinction between lower case and upper case. And guess what? There's a methods for that. So now my cones performs a case insensitive string comparison without creating new strings on the heap much better. Okay, let me summarize what we have learned in this lecture. The is mellower anti methods checks. If strings are no or zero length, it has no performance benefits over the manual check buds. Using the methods need still more compacts cold. The is no more white space methods checks if strings are No. Zero ling's or contain only white space characters. The message is faster than the usual solution off using trim because it does not allocate a new strain on the him. The string dot equals methods can before a case insensitive string comparison. The method is faster than the usual solution off using to upper or to lower because it does not allocate a new string on the
7. The using statement: in this lecture, I'm going to show you how to deal with Disposable Resource is in C sharp. Take a look at the following code snippets. So this is a fairly standard way to decrypt text in C sharp. I start with an encrypted file, feed its contents into a crypt of stream paired with a decrypt er that I said of earlier to decrypt the text on. Finally, I create a stream leader to read the contents off the crypt, a stream on return. The decrypted results. So whenever in the program, you can see that it displays unencrypted text on the console. But this code is not very robust. The file stream on script, a stream set up in memory buffers to cash their data and thes buffers remain in place until the streams get garbage collected, which may happen minutes or even hours later. So the coat is being wasteful with memory. To fix this, I need to dispose of the buffers as soon as I'm done decrypting the text. As you might know, the message for disposing system resources is called well disposed, so I'll modify my code as follows. But now I have another problem the streams will not be disposed if for some reason, the 1st 5 lines of Cold Shadow on exception. So I have to guard against the scenario. I need to wrap the codes with Try catch box like this. So you see that God's very verbose, really fast. The code is now properly protected against exceptions, but it's also a big mess off nested exception handlers on dispose statements. The readability off this code has gone downhill. Now the problem is, does we are really supposed to cold like this? Because the only sure way to guarantee that a dispose will be called is by using a finally block. So if you get tired on decides to skip a couple of exception hundreds to save time, you are setting yourself up for some really annoying debating sessions in the future. Fortunately, Microsoft has recognized this dilemma. Aunts provides us with the extremely useful using statements. You are probably already familiar with the using statements as a means to import name spaces. But there's another use. I'm going to change the coat. Now watch this. This is the exact same code the compiler takes. These using statements on expands them into full blown exception hunters with a call to the dispose method in each finally block. So you see, there's absolutely no excuse to avoid calling the dispose method. Microsoft has made it extremely easy to Fuller the to follow the proper procedure by giving us the using statements on half the compiler automatically create the complete cold fragments for us. So to summarize, always, always, always use the using statement if you are allocating some kind off scarce resource and you want to dispose off the resource when you're done, examples of scarce resource is our in memory buffers. Like in my example, file handles database connections as graphic device handles. Okay, in the second part of this lecture, I will show you some cool things you can do with the using statements you've seen that the using statements is extremely useful in setting up the proper co templates for disposing. Resource is quickly, but a disadvantage is that when you religiously put using statements all over your cult, you will get very deeply nested cold. Just look at the final version off my coat. Snipers. I am only reading a file antique. Writting it on my cold is already nested three levels deep. Imagine what the code would look like. If I would safe. They could decrypt it. Filed back to disk, I'd have cold nested six or seven little steam. Now, from a performance perspective, there is absolutely nothing wrong with deeply nested coat. But for US programmers, it's a bit annoying. Are cold moves all the way to the rights on off the screen? Off the editor arms. A large number of curly braces make the cold hard to read. But again, Microsoft comes to our rescue to avoid having deeply nested using statements. Mess up our coat. They actually recommends the following cold formatting guideline. Now check this out. So this is still the same coat. But the outermost to using statements do not have curly braces, and I am no longer in denting the statements with Tubbs. Microsoft actually approves off this coding style on the visual studio code for Motor will recognize the style and tools like style Cop will not produce warnings or errors. If the coal seems a bit weird to you, think about it as if the using statements are a list off variable declarations. You would put variable declarations at the top of your colds in a flat unindentified list on this style follows that same convention. I personally like this code style, but there are other I T professionals out there that dislike. It's because of the using statements. Sets up a cold block on code blocks should always have curly braces on Be probably indented , so use this style at your own discretion. A nice thing you can do with using statements is set up more than one declaration in a single statement. All you need to do is put all the declarations in a single using statement separated by commas. But there is one very important limitation. All the declarations need to be off the same type. Now, looking at my decryption calls, that's going to be a problem. I have one file stream, one crypto stream on one stream leader. These are all different types. So how can I combine them into a single using statement? Well, here's a little trick you can use. There is actually a single common denominator between all of these types, and that is that they are all disposable and every disposable type in dot Net has to implement the I disposable interface. So this interface is the common denominator. So all I need to do is set up three I disposable declarations like this, you notice that I need to put in to type casts as well with the as keyword, because all my variables are now off the my disposable type. So I need to cast them back to the correct type whenever I want to use them. Now. Personally, I do not find this trigger useful. You still have the same number of coward lines. And now the code is also littered with tide casts to convert the disposable variables back to the correct type. That does not really improve the readability off the cold at all. Okay, I'll conclude this lecture with two common mistakes that are often made with the using statement. I will start with this coat. No. What do you think? So this is again the flat unindentified list off using statements. But now I've pulled the variable declarations out off the using statement. The declarations go at the top on the using statements simply initialize the pre existing variables. It looks OK, doesn't it? So what's wrong with his coat? Well, the problem is that I can now access the variables after they have been disposed. The variable declarations are outside off the using block, so they remain in scope for the duration off the entire program. So I can actually do something like this. I am accessing the file stream after it has already been disposed. This is obviously wrong. I should never attempt to access disposed variables. But look what happens when I compel the code. I get no compile errors because I am not doing anything sent tactically incorrect. I'm simply accessing a variable that is still in scope. But now look what happens when I run the cold. I get the edl you've been expecting. I cannot call any methods on a disposed object. So this coding convention actually allows me to access disposed variables and trigger runtime errors. Now, that is a problem. But watch what happens when I changed the codes back to its original form on, then still attempt to access the foul stream after it has been disposed. Now look what happens when I compile this calls. You see that the compiler tells me I am accessing on out of scope variable The using statement sets up scope block on any variables declared within the using statements are inaccessible after the end off the scope. Look, this makes it completely impossible for me to access the variables after they have been disposed. So never put the variable declarations outside off the using statements because you are setting yourself up for potential run time errors when you accidentally try toe access. Indisposed object. Let the compartment protect you. The seconds common mistake I see with a using statement is called Like this. These codes sets up a Web request to access the Web page on the Internet on. Then it uses Stream Reader to read the Web response and down off the page into a string variable. So what's the problem with his coat? Well, since there's only a single using statements, only a single variable will be disposed, which in this case, is the stream reader. Now the good news is that the stream reader will also automatically dispose the underlying response stream. But that still leaves me with the http response object. This object should also be disposed as quickly as possible because it holds on toe in network socket. So the correct code would be something like this. So now I have to using statements one for disposing the http response object on one for disposing the stream leader, which will ought which will also automatically dispose the response stream. So you see that packing many objects initialization into a single using statements is possible. But you have to be very vigilant that the single call to dispose will clean up all other objects to it is very easy to accidentally overlook an object and have it lingering around after the dispose To save yourself from having to be hypervigilant all the time. It's much better to just split the initialization over multiple using statements and use a single using statements for each object. That way, nothing can ever go wrong. And if all your objects part off the same time, feel free to use the comma separated sent us. Okay, so here is a summary off. Everything recovered in this lecture. The using statements sets up a trying finally block toe automatically dispose of variable. Once you are done with it, you can nest using statements, leave out of the outermost curly braces on, not in dent your coals to improve readability this coat syntax is approved by Microsoft. You can have a single using statements set up more than one variable by separating the declarations with commerce, but only if all the variables are off the same type. Declaring variables outside of their using statements is a bad idea because it extends their scope. This allows you to access the variables after they are already disposed. Nested object initialization in a single using statements is a bad idea because the other objects might not get automatically disposed.
8. Object and collection initializers: the next schools he sharp language feature I would like to show you is the object on collection initialize er. This feature makes it very easy to set up a complex object graph with only a few lines of code. Take a look at the following snippet of code. You'll notice the auto properties in the definition Off the points class, I am setting up a simple class with two public interviewer properties, X and Y. Then, in the main program message, I declare a variable off type points on a sign values to the X and Y properties. It's pretty straightforward so far, don't you think? Just the simple bit of colds to declare at initialized User defiance type. But did you know you can reflect on this coat on? Remove two lines of source code. Let me show you. So now I Instead, she ate the point variable by calling the constructor. But then I continue the line with an opening curly brace. A list off property initialization expressions separated by commas. Andi, I end the line with a closing curly brace. This syntax is called on objects initialize er so this is a very cool syntax. You can follow any constructor call with a list off public fields or property initialization expressions. This instance Yates. Aunt Initialize is a class in just a single line of code to compact the source cold even further. You can optionally riff remove the empty parenthesis is following the constructor like this . Pretty cool, don't you think? Behind the scenes, the C sharp compile it simply takes the object. Initialize er produces the field aunt's property initialization statements to initialize the objects. So again, this feature is nothing more than syntactic sugar to help you cold, faster or checked. Initialize er's on anonymous types are very similar to initialize an anonymous type. You would use the exact same syntax as with the object initialize er, but you leave out the constructor name, so my point instant station would look like this. I removed the words point. So now the variable will contain on anonymous type with public X and Y properties. Notice that I also have to use the var keyword because I no longer know what the type off the variable will be. Objects initialize. Er's really shine when you're setting up lists off objects. So let's say I want to initialize a list off point instances, I could do it like this. So now I'm using initialization syntax with the list elements separated by commerce. This is called a collection initialize. Er. The C sharp compiler will take the source coat on produce calls to the ad's message off the list for each list Elements. Notice that I'm nesting object initialize er's inside a collection initialize er, so each list elements Here is a fully initialized point instance, with you compiler again producing the necessary property assignment statements to correctly initialized each points. Another cool trick you can use with collection initialize Er's is called a non default constructor on initialized the list only one go. For example, let's say I want to initialize my list off points to a capacity off 200 elements. I can simply do it like this. So now I'm calling the non default list constructor that allows me to specify a list capacity on. Then I simply continue the line with the collection initialized percent ups. The compiler will convert this coat into one constructor. Call on four calls to the ad message to initialize the elements off the list. Another nice thing you can do with collection. Initialize er's is set up a dictionary. Let's say I want to set up a dictionary that maps RGB color codes to their corresponding names. I can simply do this so again I'm using the collection initialize er syntax. But now each elements is contained in curly braces and contains a key value pair. The compiler will generate three calls to the ad methods off the dictionary on feed the key value pair into the method, Assuming that the first method parameter is the key on the seconds method, parameter is the value. You can also use the index or syntax toe initialize the dictionary like this. The nice thing about Initialize Ear's is that they are not limited to these standards collection classes. All they require is on I unmemorable interface on a public adds method with the method parameters that much the initialization expressions you provide so you can use the collection, initialize or syntax on any class you like. The indexer initialization syntax will work on any class with an eye unmemorable interface on on indexer with a parameter that matches the expressions you provide so again you are not limited to the standard dictionary classes. Okay, let me summarize what we've learned in this lecture objects initialize er's allow you to quickly in Stan. She ate out initialize and objects collection initialize er's allow you to quickly in Stan . She ate aunt initialized collection. Initialize er's are just syntactic sugar. Behind the scenes, The C Sharp compiler produces statements to call the constructor initialize object fields and properties. Aunt called the ad methods to feel collections collection initialize. Er's work on any class that implements the I innumerable interface and provides an answer messes with the correct parameters. The index or syntax, works on any class that implements the innumerable interface on provides an indexer with the correct parameters.
9. LINQ query expressions: in this lecture, I'm going to show you how to use link clearly expressions in your C sharp cold link stands for language. Integrated Query on It is a pretty based technology that was introduced in C Sharp version 3.5. It's lets you filter projects, join group on order collections in a very natural manner. So let's take a look. Check out of the following snippet of code. Now let's say I want to convert all the names, starting with the letter B to upper case. The classic way to do this is as follows. So now I have a list containing three names Billy, Bob and Brad all in uppercase. But this approach is not a very efficient. Those three names are coming over into a new generic list, so now the three names are stored in memory twice once in its original formats in the array on Once in upper case in the list. In my example, this is not a problem, but imagine if you have millions of items to process. A much better approach would be to create a custom and numerator that in operates each name on automatically skips over any name that does not start with a B. Andi returns each matching name in uppercase. With this approach, no additional memory is needed. You can imagine this approach to be sort of like writing a custom for each statements that performs off this filtering and processing in the background automatically. In C Sharp Division 3.5, Microsoft introduced Link a very powerful creating library that can easily perform these tasks. So now I can refund to my coast as follows. Much simpler. I'm using the wear extension messes off the system modeling name space to filter the array on the select method to project each elements to uppercase. The end result is a custom in admiration that filters out all names, not starting with the letter B on returns, each matching name in uppercase the type off the return value is a generic I innumerable off type stream. Aunt, I no longer need a genetic list to store the results, but I can improve this cold even further. Instead of calling link extension. Mrs. I can also use a link quickly Expression? Let me show you. This is the exact same coat. The C sharp compiler will take this clearly expression on, converted to the nested link extension method calls to implement the query. But now the source code is a lot cleaner without all those parenthesis is on London expressions. When I read this cold, you see the same results, Billy both on brats. In upper case, you can combine query expressions with regular extension method calls. For example, the following calls checks if there is at least one name, starting with the letter B in the array. So here I am, using a query expression toe, filter the terrain to only names that start with the letter B. I have surrounded this expression with a pair off parenthesis on. Then I call the any extension methods which checks if the enumeration contains at least one element. When I run this program now you can see that there is indeed at least one name in the you're A that starts with the letter B. This combination of a clearly expression on on extension method call works perfectly fine on. You can mix and match them at will. Now check this out. I can also group values the following expression groups names by their first letter. This will return on in admiration off key value pairs where the key is the first letter off . The name on the value is an in home aeration off all names that start with that letter. When I read this cold, you can see that I have three names starting with B two names, starting with D, M or T on one name, starting with E H I V or W. I can also order values in creating expressions. For example, let me change the coat to creates I a descending list of groups containing the names in descending order. This clearly expression has to ordering statements. The 1st 1 orders the list of names in descending order on the second statements orders the groups by key in descending order. The result is the same list of groups names as the previous example. But now, both in names on the groups will be in descending order. The nice thing about the link clearly syntax is that you can easily express very complicated queries. The syntax really shines when you're doing joints or when you are using multiple generators or if you need to store temporary variables while evaluating the creating. So I'll start by showing you a joint statements, I will join the list of names with itself on. Then I will select each name that starts with the same letter that another name ends with the creative looks like this. So this deceptively simple looking Cleary joins the name array with itself. Select each pair off names where the first letter of one name matches the last letter off another name. And then it's projects a new in admiration off anonymous classes containing these matches. You could express this query with the regular link extension method syntax, but you would have to use the select many methods to implement the joint. This would make the source cause less readable and clear. Let me run the cold and there you go. These were older, matching name pairs. So here's another example. I will use a link expression with more than one generator to create a list off all vowels in each name. This query uses two generators, the names, array and the character array of familes. The creating in operates each name, then in Emirates, each vowel on tests. If the vowel a cures in the name for each match, the creating returns a stream specifying which vowel was found in which name. Let me run the cold later, the results. Now again. You could write this clearly with the irregular link extension method syntax, but it would make the source cold, less easy to read. Finally, let me show you an example off the Let's keywords inquiry expressions. I will write a query that tests if a name is a palindrome. This clearly uses the let's keywords to declare a temporary variable inside the creative expression for each name in the names array. I used the reverse methods to create a string with all the characters off the name in reverse. Then in the wear parts off the query, I can simply test if the name matches the reverse version off that same name. When I run this query, see, you can see that Bob on Hanna are pounding drums. Okay, let me summarize what we have learned in this lecture. Link Expressions can be created by either manually calling link extension methods or by writing the creating as a query expression on half the compiler generate the corresponding C sharp extension, let it calls, creating expressions on extension method Calls can be freely mixed and matched the creative expression. Syntax is very well suited for joints, multiple generators on queries that declare temporary variables.
10. The yield return statement: In the previous lecture, I showed you a bunch of cool link clearly expressions, each expression operated on a list of names implemented as an array of strings. You learned how easy it is to use link to filter, sort group and join data in an array. But what if there is no array to creating? What if you needs to clearly a dynamic sequence off values, for example, on infinite, a range of inter jours? You might say That's easy. I'll just use the range methods like this. So this clearly returns on in admiration off all even numbers less than 100. But what if you need a more complex sequence? How about a list off all Fibonacci numbers? The Fibonacci sequence is a sequence of numbers where each number is the sum off the previous two numbers. How would you create such a sequence? Now? One solution is to compute all numbers in a trance and put them in array. But this is a wasteful solution because it requires a lot of memory to store the numbers. The better solution is to create a custom in operator. This is an object that behaves exactly like a collection but it's calculates each value on the fly when u. N m. A. Rate the elements with me for each statement, writing a custom in operator is not hard. Here is the numerator for calculating the Fibonacci sequence for numbers up to 100 this numerator produces a Fibonacci sequence for numbers below 100. Honey behaves exactly as if it were a collection. You can use a fore each loop to inaugurate each value like this. This cult will write each Fibonacci number up to 100 on the console. As you can see when I run the program, the yield return statements makes it very easy to write custom in operators like my Fibonacci sequence class. Let me show you I will re factor the colt to use the yield return statement instead. Here we go see much cleaner and shorter. So now I no longer have a class, but I have a message. Instead, the message returns on I in memorable sequence of integers. There's no current property or move next on reset methods. Instead, the coat simply uses a wild loop to calculate the feeble natural numbers on uses. The special yields of return statements to return each number in the sequence. This method produces the exact same enumeration of integers. So again I can use it for each statements like this. Then we prove to you that nothing has changed. I'm running the program now. See the exact same sequence of integers. When I compiled this cult, the C sharp compiler will take them methods and re factor. It's completely turning it into a custom in operator class. The yield return expression is placed in the current property on the remaining lines of code. In the while loop are moved into the move. Next method, the wild loop expression goes into a return statements at the end off the move next method on the wild loop itself is completely removed. This is a significant change. The compiler basically tears Michael depart on, then reassembles it into a kind of state machine with a currents property on the move next method. So now there is no longer a 1 to 1 correspondence between my source codes on the compiled cold. But the big advantage is that I can now create custom in operators with only a few lines of code. The rules for creating custom enumerators with yields return. I'm very simple. Everything you return with the yield return statement goes into the state machine, and the compiler will ensure that the generators class returns these values in the correct order. The enumeration stops when either you method ends or when you execute the special yields. Break statements. So when you put a yield return statement insider for each of a while loop the compiler changes your coat into a state machine that executes one single loop iteration every time you call. Move next. This is really nice because it means that your you'd return loop on. Lee gets executed when the values are actually needed. And not before. Let me summarize what we've learned in this lecture. You can use custom in operators to create dynamic sequences or values that behave exactly like a collection. The advantage often in operator, is that it executes only when the values are actually needed. The yield return statement makes it very easy to create a custom in numerator. The C sharp compiler re factors loops with yield return statements. Pencil estate machine that executes one loop iteration every time the move next method is called. The enumeration stops when the yields return loop ends or when you execute the yields break statements
11. Extension methods: in this lecture, I'm going to show you a very useful C sharp language feature called Extension Methods. So let's say half the following code. These cold calls and messages calls get some objects which returns some kind of value. We don't know what it is. The second line calls the two string method which is built into the object class two prints , the string representation off the objects to the console. Let me run the program. You can see that the objects is actually an engineer. This is all fine and good. But what if I want to write the X and l representation off the object to the console? I can do this manually with an XML serialize er, but that's a lot of cold. Wouldn't it be simpler if I could simply do this? Unfortunately, this will not compile. Let me show you. See, I get to compile later. The reason I get the error is because of the Objects Class does not have a built in to XML methods, so this card will never work. There's also no way I can extend the object class and add this method in. So I guess I can never use this particular syntax? Or can I? In a surprising twist, Microsoft actually allows you to do this and use this syntax. All we need to do is create an extension. Methods like this notice that this method is static on that it has the this keyword proceeding the first method parameter Now to use this methods on I need to do is call the methods like this. Let me run the coast to prove to you that it is working. Here we go. See, It works. The integer is now expressed as XML. If you've never seen extension methods in action, you might be blinking right now and thinking What the hell just happened? Well, here's the thing on extension message is just syntactic sugar. Just like many off the other language features we've seen so far the compiler takes, my source goes on reflectors. It's like this. I see the card has just flipped around the right line. Methods directly calls the static to XML methods which receives the object as a parameter. Now contrast this to my original source codes, which suggests that I'm calling the two xml Instance methods on object. Instance the compiler is performing a sleigh of hand here to make a static method look like an instance? Methods. So why would you want this? Well, most of link is implemented as extension methods that operates on the i unmemorable interface. So when you're calling the where ordered by on select methods on an arrange, which generic list, you are really just nesting a bunch of static methods that receive the unmemorable data as a parameter. This trick allows Microsoft to implement Link as a fluent AP I, despite the fact that they could not extend the iron honorable interface in any way. So our extension methods a good thing. You will find developers who think they are great and other developers who believe extension methods are pure evil. The controversy arises from the fact that these methods pretends to be something that they're not. Overuse off extension methods can make your cold less readable on a fuss stick. Eight. Your underlying platform. This will also pollutes visual studio's intelligence, pop up and make it harder to write cold assert Problem with extension methods is that they can lead to bad application architectures if you need common access to a method which is not in the base class, then your class hierarchy probably needs some redesigning, but you can completely avoid this by simply adding an extension method. So in this scenario, extension methods become a sort of band AIDS to keep a faulty class design working without having to painfully redesign everything. So, in my opinion, extension methods are a good scene, but only when used in moderation. You should only use extension methods when you cannot extend the class because of this seals or you do not own the cold. When you want to add functionality to a global type like objects or Ryan honorable or when you want to chain message together in a fluent A P I. In all other cases, it's better to just go into the class and add an instance method directly. I will give you some examples of extension methods on. You can make up your own minds if you think they are useful or not. These examples all come from a stock overflow article titles. What are you favorites? Extension methods. So you've already seen the two XML methods, which can convert any objects to XML. Here is another cool methods. Have you ever had to compare an integer variable against many literal values. You're cold, then looks like this. I've often had to write code like this when implementing online payment processors on, I had to parse an error coat. But now look at this extension methods. With this method, I can simply do this. Let me down the coast. See, it works. I've worked a lot with databases on When reading data from a database, I often needs to be able to cast value to any given type. This is fairly easy to achieve with the convert class, but extension methods take this to the next level. Check out this method. This method takes any value that implements the I convertible interface Aunt converted to any given type. So now I can simply do this. I am converting a string directly to an interview. Let's test if this works, I'm running the code now See, it works. A weird thing about the DOT net framework is that not all collection classes support the ad arranged methods, which lets you add a whole range of values to a collection in one go. But don't worry. We can create an extension method for this task So now I could feel the collection in one Go, for example, the hash set. I'm going to run the cause. Here we go. Everything works while we're on the topic of collection types, have you noticed that the list class has a very nice for each method? But other collection classes do not. Well, this extension methods provides a full each message for all collection classes. No, I can use this methods on any a nominal data. For example, the hash sets I created earlier. This will rights every value in the hash set to the console. Let me demonstrate. I'll around the coat. See, it works. So let me summarize what we have learned in this lecture extension methods are seeing tactics. Sugar. They are static methods that you can use as if they were. Instance. Methods often given plus extension methods are useful if you need to extend a sealed class or a class you do not own. They are also useful if you need to extend a global type or if you are designing a fluent A P I. Extension methods are controversial because they are first decayed to the actual objects. A p I. They pollute the intelligence pop on, they can become a band AIDS to avoid having to redesign a bat object hierarchy.
12. Lambda expressions: we've reached the final lecture off this section on, I want to show you a very nice language feature called London Expressions. So let's take a look. Let's say I have the following code snippet. I start with an integer the number five. Then I instance she ate a math operation. Delegates on pointed to the multiply method. In the next line, I call the operation, which will effectively call the multiply methods, provide the number and stole that result. So when I run this program, you can see that the result is 25. Just as expected, the advantage off using delegates is that I can easily change the mathematical operation without having to change the cold. Any message that takes an inch and returns with means can be used here, but the code is a bit for both right now, so let's clean that up. The first simplification I can perform is to use generic delegates instead, The dot net framework provides the following handy genetic delegates out of the box. The action delicate that takes a parameter off type T and returns void. The funk delegate that takes a parameter off type T and returns of value off type T results on the credit cards. Delegate that takes a parameter off type T on returns a Boolean for my colds. I will needs a generic funk delicates off type into your comma interview because I take a parameter of type into Sure not. I return a value off type integer so the code looks like this. I no longer have to declare the mass operation delegates because I'm using the built in funk genetic delegates, but we can take this one step further. Instead of having to set up a private multiply methods. I can write the entire operation in line like this. What I am assigning to the Operation Variable is called a Lambda expression. It is a one line delegates implementation that takes an integer parameter named X and returns the square off X. Now notice that I no longer needed private methods. I don't need to explicitly specify the type off X. The whole program just got reduced to only three lines of code, So here's no review off London expression syntax. I'll start with the one you've just seen. This is an in line method that takes one parameter off type team on returns an expression the compiler will infer the type off the return value on select the correct generic funk delegates. You can add as many parameters as you like, or you can have no arguments, that's all. If you need more than a simple return value, you can use multiple statements like this. You can also make an action methods that does not return a value by simply leaving out the return statement on. Here are the rules. When using Lambda expressions when you are assigning and Lunda expression toe a delegate. The following rules apply. The Lunda must contain the same number of parameters as the delegates type. Each input parameter must be implicitly convertible to its corresponding delicate parameter . The return value off the Lambda, if it exists, must be implicitly convertible to the delegates return type. These rules will probably not surprise you, but the nice thing here is that you do not have to match the delegate types exactly. Everything will work fine as long as there is an implicit conversion from the London type to the delicate type. So, for example, when a delegate expects long parameters, you can provide a London expression that uses integers instead. Because there is an implicit conversion from Inter show too long on this will work fine. London expressions can refer to variables that are declared inside. On the outside of the expression, referring to an outside variable is called Capturing the Variable Again. There are some rules you cannot capture on initialized variables. Variables introduced within the London expression are not visible in the outer methods. A Lunda cannot capture a ref or out parameter. Andi in Lunda cannot contain a go to break or continue statement that jumps outside of the expression. The reverse is also not allowed. Once in you need to watch out for is that the captured valuables will remain a life for as long as the delicate exists. This can leads to a peculiar scenario where a variable ghost out of scope, but it remains a life because it has been captured in a Lunda that remains in scope. This is a very common source off memory leaks in dot net applications. Now I'll show you how to set up a simple cancellation handler for a console application, so this codes will run when I press control. See on the console. Let me demonstrate. See it works now. Notice in the source coat that I don't provide types anywhere. My lambda expression specifies the names off the input parameters, but not there types. This is perfectly valid if the compiler can infer the types from the cancel key press delegates. This is a very nice application off type inference. It extends to the parameters off Lambda expressions. So most of the time you do not need to provide any types. That's all. The compiler will figure everything out. Another nice thing you can do is change expressions together. Let's say I want to create a whole range off cancel event handlers with a different message every time I could do it like this. Notice Lee chaining syntax. I have a Lunda that returns for Lunda, not returns and even under. So this sets up a London that takes a single message parameter, and it returns Another lambda that expects Ascender on an event or experimenter. So I have effectively created the Lunda that creates blunders. I can use it like this. Each cool to make handler sets up a new event under with this specifies mass message. Let me run the cold, see everything works. This chaining off Lunda expressions together is extremely powerful. Okay, here is a summary off what we have learned in this lecture. Lunda expressions are in line methods that can be assigned to delegates. If you do not specify the parameter types the compiler will in for them. For you, Londoners can refer to variables inside and outside of the expression. Referring to an outside variable is called capturing the variable captured variables remain in memory until the delegate is garbage collected. This can lead to unexpected memory leaks. You can chain Landers together to create Londoners that return Londoners.
13. The null conditional operator: Okay, let's get started with our list. Cool C. Sharp language features introduced in the latest version. Six. As you recall, we started the previous section with the no coalescing operator hands in this lecture, I would like to show you its cousin, the no conditional operator. So let's say I have the following methods in my projects. So this method takes a string value and then truncate sits to the given number of characters Sounds. The midden method called ensures that the value is truncated to no more than the actual length off the value. I can call this method in my cold like this. That's when I run the cold. You see that it correctly writes Mark Fucker to the control the 1st 9 letters of my full name. But now watch what happens when I specify and no value for the string. Let me on the program again. You see that it gets that dreaded no reference exception in the court to sub string, and this makes perfect sense within the truncate methods. The value parameter is now no. So I can't recklessly call the sub string methods on it. I need to first reform an explicit check from No. Now again, As I said before in the lecture on the no coalescing operator, there is nothing wrong with a null check, but they can get a bit tedious if you have to write hundreds of them in your project. Fortunately in C sharp six, you no longer have to do this. You can now simply write this now, watch what happens when I run the girls. I see no more no reference exception. And now the Colts correctly writes the default string to the console. So what's happened here? Well, I used the special no conditional operator, which you write out as a question mark on a period. The operator works just like the irregular periods in that it accesses a fields, a property or a methods in an object instance. But when the object instance is no, the conditional operator simply returns No. So, in fact, this line gets converted by the compiler into this line. But with the extra benefit that the value is only evaluated once so again, this is a form of syntactic short C sharp six gives us a compact and efficient way to perform a null check. I'm gonna make a change to my truncate, Mrs. I will alter the method so that is always pads the value back to the original length. So if I take my full name, which is 14 characters in length on I truncated to nine characters, then I want the method to pad the truncated name with five additional spaces to get back to a result off 14 characters. This is very easy to accomplish. I simply need to do this again. He was a call to the max methods to make sure that I don't pad a negative number of spaces . So now what do you think happens when I provide a no value? We know that the sub string method will not be called. But what about the pads? Right method? Do I need to replace every periods in my call chain with the no conditional operator? So basically, what I'm asking here is how the compiler transforms this line of code like this or like this. It's a subtle difference, but with profound consequences. If the value is no, the first transformation will work fine, but the second transformation will throw and no reference exception. Well, let's find out the answer and he's going to run the program and we'll see what happens. Here we go check it out. Everything still works. So that answers the question. It's the first transformation I showed you. What's happening here is a process called no propagation. If you use the no conditional operator on the expression to the left off the operator is no , then absolutely nothing on the right hand side off, the operator gets executed. The no conditional operator short circuits the evaluation as immediately returns. No, this is super handy because it means that you only need to place the no conditional operator of the start of your call chain. Every subsequent coal can use the regular period operator, and no propagation will ensure that these calls get properly skipped if the instances no. Okay, so here is another challenge for you. Check out the following cold. This code works fine. As you can see whenever on the program, it's simply displaced zero on the console. But here's a question for you. What is the type off the Len variable? That's a bit of a mystery. If the name is not know, then it's obviously an integer. But what if the name is no. Is it the stream? An old checked something else? Well, again, Let's find out. I will put a break points on the right line. Statements on Then run the program in the development. Here we go. Okay, so now the program is suspended. That's the right line statements. Now, when I look in the locals window here, you can see that the Len Variable is a notable integer. This makes perfect sense. If the right hand side off the no conditional operator evaluates toe value type, then the results off the operation is the knowledgeable version off that value type. So in my coat example, the variable becomes inaudible into. I can remove the var keyboards on explicitly, right out the type 1000 notable ins like this. There's a nice symmetry to the source calls with question marks on the left and right hand side of the assignment operator to remind us that we are dealing with a notable assignments and in the right line, statements you see there old friend than no coalescing operator show up again to provide a default value. If the name is no, I can also declare the variable as a no notable in future and you see no coalescing operator supervise a default value like this. So now the variable evaluates to an explicit, non knowable integer on this nicely cleans up the right line statements. Okay, so here is another example. You've learned all about extension methods on the yield return statements in the previous section. So now I am going to combine these two. Check this out. So this extension methods picks a specified set off items from a list and returns them as an enumeration. But the message automatically skips over any no items and only returns none. No items, so I can run this code as follows. Let me on the program. Here we go and you see that I only get the no no values on the console. I'm using the no conditional indexing operator in my methods, which you write out as a question mark, followed by an opening square bracket. This will index a collection or in admiration, instance, unless that instances no, In which case, the operator short circuits on simply returns. No. So you see that there are two versions off the no conditional operator, one with a periods which accesses a field property or methods often object instance. And one with the square brackets, which accesses the indexer. Often object. Instance, Both operators short circuits. If the instances no, in which case they immediately returned. Now, without evaluating the expression on the right hand side of the operator. Keep in mind that is he no conditional indexing. Operator does not distinguish between a no object Instance. Four. A valid object instance that just happens to contain a value. No. If you need to distinguish between these two, then you will have to perform the test manually. I'm going to show you one last example on how to use the no conditional operator. Check out the following coat. You will recognize our old friends a little under expression being signed to a generic function delegates. So this coat takes the number five, squares it by calling the operation on, then writes the result out to the control. But what if the delicates isn't no like this? Now? The second line off codes will throw a no reference exception because the delicate is no. So I need to add a check for no before I can safely invoke the delegates. You always need to check for no before invoking delegates. There is no getting around it. Well, until now, it is with the no conditional operator. Thank into this. I used the no conditional operator to safely call the invoke methods on the delegates on a short circuit to know if the delicate is no. Then I used the familiar, no coalescing operator to provide a default value off. Zero. If the result is no, let me run the program and you see that I get the value zero just as expected. So this is a great technique to avoid typing out the null check when you invoked delegates . Simply use the no conditional operator on follow it with the invoke methods. And again, keep in mind that a no conditional delegates in vocation does not distinguish between a no delegates or a valence delegates. That just happens to return. No, if you need to distinguish between these two, then you'll have to perform the test manually. Okay, here is a somebody off what we have learned in this lecture. The no conditional operator returns. No. If the expression on the left hand side of the operator is no the operator short circuits any additional invocations in the cold chain on the right hand side of the operator. If the expression on the left off the operator is no, the operator returns a knowledgeable type. If the expression on the right hand side off the operator returns value type, the operator supports delegates invocation in the threat safe manner. The operator is available as both a member off a razor and as an indexing operator.
14. Auto property initialisers: the next schools he sharp six feature I would like to show you is the also property initialize er remember In the previous section when we talked about auto properties, we discussed why you would want to use properties because you could also simply use public field like this. This is the same code snippets I showed you in the Outer Properties lecture. I am simply using a public field here, but notice that I also added on objects initialize er so this person class gets inst enshi ated with my name as the default. Now you learned that there are many good reasons for using out of properties instead of public fields. So I should really use this coat instead. But now I have a problem. I can no longer initialized the auto property backing field with the object initialize er so to initialize in the name, I will have to add a default constructor and do the initialization there. That's a lot of extra code just for a simple field initialization on it makes you want to go back to just using public feels instead. Fortunately, c sharp six comes to the rescue. Now you can initialize the property exactly in the same way as she would initialize the fields like this. This sets up a string property called name also generates a getter on the center on. Then initialize is the backing fields with my name. Well, in a single line of code, you might be thinking that Microsoft is going a little overboard with colds out old generation. But look at it this way. It's very nice that this syntax for initializing a property is now exactly the same as the syntax. For initializing a field, you no longer have to memorize the arbitrary rule that objects initialize. Er's don't work on properties. There's no reason why they shouldn't. And now Microsoft has removed that limitation. In the Auto Properties lecture from the previous section, I showed you how to create on immutable type. This is a class that you can only initialize in the constructor and from Zen, um, it's internal states cannot change. I implemented the musical type with an out or property with only and get her. The C sharp compiler recognises that I want to create on immutable type on automatically generates a read only backing fields. So what's if I want to Cody aids on in musical type with a default value. Well, now you can simply do this. Notice that I removed the settle from the outer property, the compiler in first that I want the person type to be immutable on so it generates a read only backing fields and a public property getter. But now it also initialize is the backing fields to my name. These coals might seem a little bit weird to you because I am basically setting up a constant here. But remember that the initialization expression can be any static expression. Ondas complex as you like, for example, to initialize the name property to the current locked in user. You can do this, and here's another example I can combine on immutable. Also property with lazy loading to create a factory. Instance methods in a single line of code like this. This sets up on immutable outer property called current, that lazy instance Yates to a new person. Instance, the first time it's called This is a completely functional factory instance pattern with lazy loading. Okay, here is a somebody off what we have learns in this lecture. You can pads objects, initialize er's to alto properties by following the property declaration with on initialization expression, you can also initialize immutable alto properties that only have together also property initialize. Er's can be complex expressions that call static methods. You can combine immutable. Also, properties with the lazy Class two creates factory instance methods.
15. Declaration expressions: in this lecture, I'd like to show you declaration expressions, consumer. The following code snippets. This loop reads characters from the console until I press the enter key the while loop tests the first character on If it is not a line feed coat, it's, writes Lee character to the console. Then the cold reads. The next character on the loop repeats You often see called like this in C Sharp projects, with the read methods repeated twice in the loop. The reason for this is that in a single loop inspiration, we need toe, read the character, test it and write it with the console. I cannot support multiple read statements in the loop body, and I have to read to the character before entering the loop to make sure I don't write any line feeds called Still Console Declaration expressions make it's very easy toe simply five discos, and you see them crop up very often in other languages that support them, Mike See or javascript on. The good news is that Microsoft has now added declaration expressions to see Show up. Six. So now I can the defense of the codes like this. So now the assignment happens inside the while loop, Check the coat, assigns the input variable on, then immediately checks is if the variable doesn't notes. Contain a line feeds cold, then the loop continues by writing out the character on the loop repeats. This change has greatly simplified the source code. Another cool thing you can do with his declaration expressions is lazy loads properties when they are first calls. Do you remember the lecture on the no coalescing operator in the previous section, where I created a stunning builder property with lazy loading? The count's looked like this. So here the cold on the right hand side off the known coalescing operator is a declaration expression. So this property returns the buffer field. If it does not know. But if the buffer is no, then the codes performs on on the flight initialization off the buffer and then returns it by using a declaration expression. This is a compact way off. Writing lazy loading properties on the source code is now very readable. Okay, let me summarize what we have learned in this lecture declaration. Expressions are assignments that behave like expressions. Declaration expressions return what is on the right hand side off the assignment operator. You can use declaration expressions to remove double assignments. Ensure methods are only called ones ons implements lazy loading properties.
16. Expression-bodied functions and properties: in the previous section, I showed you how to use Lunda expressions. These are compact in line functions that you can easily assigned to a delegates, for example, like this. So this sets up a delegate that expects a single interview parameter as returns interest your value, which is the square off the specified parameter. London expressions are super handy ways to express compacts in line functions and link uses them everywhere. So if you're new to see sharp, you might be wondering why you can't use London expressions in regular functions like this . This syntax seems perfectly logical. I am setting up a function here called Operation that expects a single interview parameter and returns the square value as an integer and in place off the method body. I use a London expression Swords off like the objects initialize er, syntax. Unfortunately, this code will not compile bus. Microsoft has recognized this discrepancy in the use of Lambda expressions as now in C sharp six, you can use Lambda expressions in the regular function declarations. Check out the following cold sniffers. Now I can use the class like this notice that I use in line objects initialize er here to set up the person instance on the right line. Methods will call the to string methods to get the string representation off the object, and this will then call my Lunda expression that simply joins the first name and last name together. Let me run the codes. Check this sounds. There you go. That's my name. So that's on expression. Body function. In a nutshell. It is simply a function declaration where you provide the function body as a lumber expression. There is nothing special going on here. It's simply a more compact way off declaring functions in your coat. The nice thing about this feature is that it lets you use Lambda expressions anywhere, both in delegate assignments on when declaring regular functions. You no longer have to remember arbitrary rules about when they are allowed or not, so that's covers functions. But what about properties? It won't surprise you that you can also use lumber expressions when declaring properties. However, there is one simple rule you need to follow. The property cannot have a center Now this makes perfect sense. When you think about it. What would happen when you set on expression, bodies, property. It makes no sense. So here is my person class again. But now with an extra property that checks if the person has a first name notice that I do not specify a get her like when I'm setting up on alto property. In this syntax, the Lunda arrow directly follows the property name without specifying gets or sets keywords . The compiler takes my London expression on Creates a property getter around this. So now the property has first name checks. If the first name off the person was provided. If so, the property returns true. Let's check what happens when I run this cold. Here we go and you can see that I have indeed specifies my first name when setting up the person instance. Okay, let me summarize what we have learned in this lecture expression body functions are functions where you provide the implementation as a Londoner expression, expression bodies, properties are properties where you provide the implementation as a Lunda expression expression bodies properties are read only so you cannot use the center
17. Await in catch and finally: my next see shop language feature is deceptively simple. Did you know that you could not use the weight keyboards in a catch or finally, statements? The reason for this is that the compiler performs some pretty radical code conversions every time you use the await keyword, and Microsoft could not figure out how to reconciling this cold transformation with an exception handler, Compare this to the yield return statements, which you saw previously When you use you'd return in a loop. The C sharp compiler tears your codes of parts completely removes a loop, moves the loop body into a new in numerator class on shuffles the cards around to generate a state machine. The awaits keyboards works the same way Every time you use await, the compiler performs a significant re factoring off your coast to ensure that the message you're calling can actually run a synchronously from the cooler friends hands any a sink. Medicals inside a catch or finally block simply didn't survive this re factoring process. But like all things that seem impossible at the outset, some Microsoft engineers sat down and had a good think about it on. They actually figured out a way to do it after all. So now this limitation is lifted in C sharp six. Take a look at the following codes so these codes a synchronously requests my bite sized. She sharpened blawg, but I made a typing mistake in the U. R L. It says, bite sized sharp instead off by sized C sharp. So now this codes will throw a Web exception. When I run it, I have folded a try catching block around this cold snippets pounds. I catch the Web exception. Then I looked. The error on the logging method looks like this. So these methods simply logs the exception to a file. But as an a synchronous operation, this code snippets retains the asynchronous method pattern throughout the entire try and cash block. At no point, um, I forced to make a synchronous call because the compiler does not support it. So let me summarize what we have. Lawrence in this lecture, when you use awaits the compiler, the reflectors, your coat to ensure that the methods can execute a synchronously. Until now, this re factoring in plight that you could not use a weight in a catch or finally block what's in c sharp. Six. This is now possible
18. Course recap: Congratulations. You have completed the entire course. You've now been introduced to advanced C Sharp language features. I have shown you how to spice up your coat with the variety off advanced features like extension methods, custom in operators known, coalescing and conditional Operators link query expressions hands much, much more. You have most of the following Advanced language features. The known coalescing operator. Soft type casts, auto properties, studying methods, the using statements, objects and collection initialize er's link equity expressions. The yields, returns statements, extension methods. Andi Lunda Expressions. You were also now up to speed with then new language features in C Sharp Version six. You have mastered the following the no conditional operator. Also, property initialize er's declaration expressions, expression, body's functions and properties on the Yusof awaits in catch, and finally, these skills will help you write better, cleaner and more compacts cold. If you discover some interesting insights off your own, please share them in the course discussion forum for us all to enjoy Good Bye, and I hope we meet again in another course