New features of C × 7.0

Time:2021-3-29

Out variable

You can use out to declare variables directly in a methodint.TryParse(“123”, out var result); 

tuple

Declaration of tuples

var alphaBetaStart = (alpha: "a", beta: "b");
Console.WriteLine($"{alphaBetaStart.alpha}{alphaBetaStart.beta}");

Deconstruction and tuple

private class User
{
  public string Name { get; } = "Bob";
  public string Email { get; } = "[email protected]";
  public int Age { get; set; } = 25;

  //Deconstruction
  public void Deconstruct(out string name, out string email)
  {
    (name, email) = (Name, Email);
  }
}

//Deconstruction元组
var u = new User();
var (name, email) = u;
Console.WriteLine($"{name}{email}");

Abandon yuan

//Abandon yuan
 var (_, email2) = u;
 Console.WriteLine($"{email2}");

Use_ Instead of the return value name of deconstruction

pattern matching

What is pattern matching

The definition of the official document is: pattern matching is a function that allows you to assign methods to properties other than object types. In short, for the abstract methods of an abstract object, different subclasses have different implementations. Now we can also use the is key to determine the categories of properties and perform different operations

if (input is int i)
{
    Console.WriteLine ($"{I} is an int type");
}
else if (input is string j)
{
    Console.WriteLine ($"{J} is a string type");
}

private object input = "123";

Switch matching pattern

The above example is the pattern matching of is. Using switch, you can write more complex pattern matching

New features of C × 7.0New features of C × 7.0

var nus = new List
            {
                1, 2, 3, 4, 5, -1, -8, -10
            };
            var sequence = new List
            {
                0, -10, -20, 10, new User(), 20, "book", "doom", "time", nus
            };

            //Pattern matching of switch
            foreach (var content in sequence)
            {
                var sum = 0;
                switch (content)
                {
                    case 0:
                        Console.WriteLine("0");
                        break;
                    case IEnumerable child:
                    {
                        foreach (var item in child) sum += item < 0 ? item : 0;
                        Console.WriteLine($"child:{sum}");
                        break;
                    }
                    case int n when n > 0:
                        Console.WriteLine($"n:{n}");
                        break;
                    case string s when s.Contains("oo"):
                        Console.WriteLine($"s:{s}");
                        break;
                    default:
                        Console.WriteLine("default");
                        break;
                }
            }

View Code

Ref local variables and return results

For reference type A, if a is assigned to B (b = a), changing the value of B will change a as well. For value type (such as int), if D is assigned to C, change the value of C, and the value of D remains unchanged. Now use the ref keyword to change the value of D caused by C

int x = 10;
Ref var num = ref X; // use ref to assign the value of X to num. although it is struct, changing num will also change x, and vice versa, which means num and X are reference types
num = 9;

If x is output, its value is 9

 

It can also be used in methods

        public ref int RefVariable(int[,] matrix)
        {       
            for (var i = 0; i < 3; i++)
            {
                for (var j = 0; j < 3; j++)
                {
                    if (matrix[i, j] % 2 == 0)
                    {
                        return ref matrix[i, j];
                    }
                }
            }
            throw new InvalidOperationException("Not found");
        }

At this point, if you change the return value, the value of the two-dimensional array represented by matrix will also change

Local function (local function)

public IEnumerable LocalFunction(int min,int max)
        {
            if(min < 0 || min > 10)
                Throw new argumentexception ("Min range is 0 to 10");
            if (max < 0 || max > 10)
                Throw new argumentexception ("max range is 0 to 10");
            if(min > max)
                Throw new argumentexception ("Max must not be less than Min");
            return Get24();

            IEnumerable Get24()
            {
                for (int i = min; i < max; i++)
                {
                    if (i == 2 || i == 4)
                        yield return i;
                }
            }
        }

Property expression

        private string _name;

        public string Name
        {
            get => _name;
            set => _name = value ?? string.Empty;
        }

Common asynchronous return type

/// 
        ///Using valuetask instead of reference type task
        /// 
        /// 
        private async ValueTask Func()
        {
            await Task.Delay(10);
            return 5;
        }

Improvement of digital text syntax and default text expression

Improvement of digital text grammar

/// 
        ///Improving the syntax of digital text_ Segmentation is easy to read and does not affect the value
        /// 
        public void NumberText()
        {
            int a = 0b0001_0001;
            int b = 100_100;
        }

Default text expression

/// 
        ///Default text expression
        /// 
        public Func Func1 { get; set; } = default;