search
HomeBackend DevelopmentC#.Net TutorialTake you through C#7 feature code examples

Take you through C#7 feature code examples:

Tuple value type

.NET provides a tuple type, but there are various problems when using it in C#. Since the tuple type is a reference type, you can probably avoid the GC overhead of using it in some performance-sensitive code. At the same time, tuple types are immutable, and while this makes sharing across threads safer, it also means that a new object must be allocated every time a change is made.

To deal with this problem, C# 7 will provide a tuple of value types. This is a mutable type, which will be more efficient for code that values ​​performance. Also, as a value type, it makes a copy every time it is allocated, so there is little risk of multi-threading issues.

You can create a tuple with the following syntax:

var result = (5, 20);

You can also choose to name the values ​​in the tuple, which is not required but just makes the code more readable.

var result = (count: 5, sum: 20);

You might be thinking, "Great feature, but I can write it myself." But the next feature is the highlight.

Multiple return values

In C-like languages, returning two values ​​from a function is always a hassle. You can only choose to encapsulate the result into some structure or use output parameters. Like many functional programming languages, C# chooses the first way to provide you with this feature:

(int, int) Tally (IEnumerable<int> list)

As you can see, there is a basic problem with using generic tuples here: we will have no way of knowing what each field does. Therefore, C# chooses to name the result via a compiler trick:

(int Count, int Sum) Tally (IEnumerable<int> list)

We need to emphasize one point here: C# does not generate a new anonymous type. What you get is still a tuple, but the compiler will assume that its properties are Count and Sum instead of Item1 and Item2. Therefore, the following lines of code are equivalent:

var result = Tally(list);
Console.WriteLine(result.Item1);
Console.WriteLine(result.Count);

Please note that we do not yet have multiple assignment syntax. If this syntax is finally implemented, its usage may be like this:

(count, sum) = Tally(list);

In addition to providing simple functional functions, the utility of multiple return values ​​is also reflected in the writing of asynchronous code, because out parameters are not allowed in async functions.

Pattern Matching: Improved Switch syntax blocks

The most common complaint about C# from VB and functional programmers is that the switch statement in C# has very limited functionality. VB developers want to be able to do range matching, while developers who are used to F# or Haskell want to be able to use decomposed pattern matching. C# intends to provide both features.

When pattern matching a type, you can create a variable to hold the result of the cast. For example, when using the switch statement on a System.Object, you can write the following code:

case int x:

If the object is of numeric type, the variable x will be assigned a value. Otherwise, the program will check the next case statement block in order from top to bottom. If you want to be more specific with your match, you can also use range checking:

case int x when x > 0:
case int y:

In this example, if the object is a positive integer, the x code block will be executed. If the object is 0 or a negative integer, the y code block will be executed.

If you need to check for null values, just use the following syntax:

case null;

Pattern Matching: Decomposition

So far, we have only shown some incremental improvements to existing features in VB. The real power of pattern matching lies in decomposition, which can completely take an object apart. Consider the following syntax:

if (person is Professor {Subject is var s, FirstName is "Scott"})

This code accomplishes two things:

  1. It creates a local variable s and assigns it the value ((Professor)person).Subject.

  2. It performs an equality check ((Professor)person).FirstName == "Scott".

If it is rewritten in C# 6 code, it will look like this:

var temp = person as Professor;
if (temp != null && temp.FirstName == "Scott")
{
    var s = temp.Subject

In the final release, we expect to see both improvements to switch blocks.

Return

Passing a large data structure by reference is much faster than passing by value, which requires a copy of the entire structure. Similarly, returning a reference to a large data structure can also improve speed.

In languages ​​like C, you can return a reference to a structure through a pointer. This approach brings about a common problem, that is, the memory pointed to by the pointer may have been reclaimed for some reason.

C# avoids this problem by using a reference, which is a pointer with rules attached. The most important rule is that you cannot return a reference to a local variable. If you try to do this, the stack information referenced by the variable will become inaccessible when the function returns.

在微软的展示代码中,它所返回的引用指向一个数组中的某个结构。由于它实质上是指向数组中某个元素的指针,因此随后可以对数组本身进行修改。举例来说:

var x = ref FirstElement(myArray)
x = 5; //MyArray[0] now equals 5

这一语法的用例是对性能高度敏感的代码,在大多数应用中都无需使用这一特性。

二进制字面值(Binary Literals)

此次发布还引入了一个小特性,即二进制字面值。这一语法只是一个简单的前缀而已,例如5可以表示为“0b0101”。这一特性的主要用例是设置基于flag的枚举,以及创建位掩码(bitmask),以用于与C风格语言的互操作。

本地函数

本地函数是指在另一个函数中所定义的函数。第一眼看来,本地函数似乎只是比匿名函数稍好的一种语法。但它实际上还存在几个优点:

  • 首先,你无需为其分配一个委托以保存该函数。这不仅减少了内存压力,同时还允许编译器对该函数进行内联操作。

  • 其次,在创建闭包时,也无需为其分配一个对象,因为它能够直接访问本地变量。这一点同样能够改善性能,因为它也减少了GC的压力。

按照第二条规则推算,你将无法创建一个指向本地函数的委托。这一点对于代码的组织其实是一个优点,因为你无需创建独立的函数,并且将现有函数的状态作为显式的参数进行传递。

部分类的改进

最后演示的特性是一种处理部分类的新方式。在过去,部分类的应用是基于代码生成优先的概念而出现的。所生成的代码将包含一系列部分方法,开发者可以选择实现这些方法,以调整类的行为。

通过新的“replace”语法,开发者就多了一种新选择,能够以最直接的方式编写代码,随后再引入代码生成器,并重写这些方法。以下将通过一个简单的示例表现开发者的代码编写方式:

public string FirstName {get; set;}

简单又清晰,但完全不符合XAML风格应用的写法。因此,代码生成器将生成如下代码:

private string m_FirstName;
static readonly PropertyChangedEventArgs s_FirstName_EventArgs =new PropertyChangedEventArgs("FirstName")

replace public string FirstName {
    get {
        return m_FirstName;
    }
    set {
        if (m_FirstName == value)
            return;
    m_FirstName = value;
    PropertyChanged?.Invoke(this, m_FirstName_EventArg);
}

通过“replace”关键字,所生成的代码将直接替换手写的代码,添加所缺失的功能。在这个示例中,我们甚至还能够处理一些开发者经常会忽略的麻烦的部分,例如对EventArgs对象进行缓存。

虽然这个官方示例仅用于属性变更通知,但这一技术还可用于各种“面向切面编程(AOP)”的场景,例如在代码中注入日志记录、安全检查、参数校验以及其他各种繁琐的样板式代码。

如果读者想实际了解一下这些特性,可以观赏Channel 9中的视频“The Future of C#”。


The above is the detailed content of Take you through C#7 feature code examples. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
C# .NET in the Modern World: Applications and IndustriesC# .NET in the Modern World: Applications and IndustriesMay 08, 2025 am 12:08 AM

C#.NET is widely used in the modern world in the fields of game development, financial services, the Internet of Things and cloud computing. 1) In game development, use C# to program through the Unity engine. 2) In the field of financial services, C#.NET is used to develop high-performance trading systems and data analysis tools. 3) In terms of IoT and cloud computing, C#.NET provides support through Azure services to develop device control logic and data processing.

C# .NET Framework vs. .NET Core/5/6: What's the Difference?C# .NET Framework vs. .NET Core/5/6: What's the Difference?May 07, 2025 am 12:06 AM

.NETFrameworkisWindows-centric,while.NETCore/5/6supportscross-platformdevelopment.1).NETFramework,since2002,isidealforWindowsapplicationsbutlimitedincross-platformcapabilities.2).NETCore,from2016,anditsevolutions(.NET5/6)offerbetterperformance,cross-

The Community of C# .NET Developers: Resources and SupportThe Community of C# .NET Developers: Resources and SupportMay 06, 2025 am 12:11 AM

The C#.NET developer community provides rich resources and support, including: 1. Microsoft's official documents, 2. Community forums such as StackOverflow and Reddit, and 3. Open source projects on GitHub. These resources help developers improve their programming skills from basic learning to advanced applications.

The C# .NET Advantage: Features, Benefits, and Use CasesThe C# .NET Advantage: Features, Benefits, and Use CasesMay 05, 2025 am 12:01 AM

The advantages of C#.NET include: 1) Language features, such as asynchronous programming simplifies development; 2) Performance and reliability, improving efficiency through JIT compilation and garbage collection mechanisms; 3) Cross-platform support, .NETCore expands application scenarios; 4) A wide range of practical applications, with outstanding performance from the Web to desktop and game development.

Is C# Always Associated with .NET? Exploring AlternativesIs C# Always Associated with .NET? Exploring AlternativesMay 04, 2025 am 12:06 AM

C# is not always tied to .NET. 1) C# can run in the Mono runtime environment and is suitable for Linux and macOS. 2) In the Unity game engine, C# is used for scripting and does not rely on the .NET framework. 3) C# can also be used for embedded system development, such as .NETMicroFramework.

The .NET Ecosystem: C#'s Role and BeyondThe .NET Ecosystem: C#'s Role and BeyondMay 03, 2025 am 12:04 AM

C# plays a core role in the .NET ecosystem and is the preferred language for developers. 1) C# provides efficient and easy-to-use programming methods, combining the advantages of C, C and Java. 2) Execute through .NET runtime (CLR) to ensure efficient cross-platform operation. 3) C# supports basic to advanced usage, such as LINQ and asynchronous programming. 4) Optimization and best practices include using StringBuilder and asynchronous programming to improve performance and maintainability.

C# as a .NET Language: The Foundation of the EcosystemC# as a .NET Language: The Foundation of the EcosystemMay 02, 2025 am 12:01 AM

C# is a programming language released by Microsoft in 2000, aiming to combine the power of C and the simplicity of Java. 1.C# is a type-safe, object-oriented programming language that supports encapsulation, inheritance and polymorphism. 2. The compilation process of C# converts the code into an intermediate language (IL), and then compiles it into machine code execution in the .NET runtime environment (CLR). 3. The basic usage of C# includes variable declarations, control flows and function definitions, while advanced usages cover asynchronous programming, LINQ and delegates, etc. 4. Common errors include type mismatch and null reference exceptions, which can be debugged through debugger, exception handling and logging. 5. Performance optimization suggestions include the use of LINQ, asynchronous programming, and improving code readability.

C# vs. .NET: Clarifying the Key Differences and SimilaritiesC# vs. .NET: Clarifying the Key Differences and SimilaritiesMay 01, 2025 am 12:12 AM

C# is a programming language, while .NET is a software framework. 1.C# is developed by Microsoft and is suitable for multi-platform development. 2..NET provides class libraries and runtime environments, and supports multilingual. The two work together to build modern applications.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.