C ා basic syntax - pass value, output, reference, array, name, optional parameter, extension method

Article directory

1, Value parameter

1. Value transfer parameter → value type

                 ;
   above the dotted line, within the method.

The   value parameter creates a copy of the variable
Action on a value parameter does not affect the value of the variable

    class Program
    {
        static void Main(string[] args)
        {
            Student stu = new Student();
            int y = 100;
            stu.AddOne(y);//101
            Console.WriteLine(y);//100
        }
    }

    class Student
    {
        public void AddOne(int x)//Value parameter x; int value type
        {
            x = x + 1;
            Console.WriteLine(x);
        }
    }

2. Pass value parameter → reference type, and create a new object


                     .

    class Program
    {
        static void Main(string[] args)
        {
            Student stu = new Student() { Name = "Tim" };
            SomeMethod(stu);//Tom
            Console.WriteLine(stu.Name);//Tim
        }

        static void SomeMethod(Student stu)
        {
            stu = new Student() { Name = "Tom" };
            Console.WriteLine(stu.Name);
        }
    }

    class Student
    {
        public string Name { get; set; }
    }

The    Object.GetHashCode() method is used to get the hash code of the current object. The HashCode of each object is different.
   use HashCode to distinguish two stu objects with the same Name

    class Program
    {
        static void Main(string[] args)
        {
            Student stu = new Student() { Name = "Tim" };
            SomeMethod(stu);//46104728,Tim
            Console.WriteLine("{0},{1}", stu.GetHashCode(), stu.Name);//12289376,Tim
        }

        static void SomeMethod(Student stu)
        {
            stu = new Student() { Name = "Tim" };
            Console.WriteLine("{0},{1}",stu.GetHashCode(),stu.Name);
        }
    }

    class Student
    {
        public string Name { get; set; }
    }

3. Pass value parameter → reference type, only operate object, do not create new object


                     .
   because as a method, the main output is still the return value. We call this operation of modifying the value of the object referenced by the parameter side effect, which should be avoided in normal programming.

    class Program
    {
        static void Main(string[] args)
        {
            Student stu = new Student() { Name = "Tim" };
            UpdateObject(stu);
            Console.WriteLine("HashCode={0},Name={1}", stu.GetHashCode(), stu.Name);
        }

        static void UpdateObject(Student stu)
        {
        	//Operations to modify values referenced by parameters, side effects of methods, side effect
            stu.Name = "Tom";
            Console.WriteLine("HashCode={0},Name={1}",stu.GetHashCode(),stu.Name);
        }
    }

    class Student
    {
        public string Name { get; set; }
    }

2, Reference parameter

1. Reference parameter → value type


   reference parameters do not create copies of passed in variables
   the reference parameter points directly to the memory address pointed to by the variable

    class Program
    {
        static void Main(string[] args)
        {
            int y = 1;
            IWanSideEffect(ref y);
            Console.WriteLine(y);//101
        }

        static void IWanSideEffect(ref int x)
        {
            x = x + 100;
        }
    }

    class Student
    {
        public string Name { get; set; }
    }

2. Reference parameter → reference type, create new object

    class Program
    {
        static void Main(string[] args)
        {
            Student outterStu = new Student() { Name = "Tim" };
            Console.WriteLine("HashCode={0},Name={1}", outterStu.GetHashCode(), outterStu.Name);
            Console.WriteLine("=================================");
            IWanSideEffect(ref outterStu);
            Console.WriteLine("HashCode={0},Name={1}", outterStu.GetHashCode(), outterStu.Name);
        }

        static void IWanSideEffect(ref Student stu)
        {
            stu = new Student() { Name = "Tom" }; //Assign new value to reference parameter
            Console.WriteLine("HashCode={0},Name={1}",stu.GetHashCode(),stu.Name);
        }
    }

    class Student
    {
        public string Name { get; set; }
    }

3. Reference parameter → reference type, do not create a new object, only change the object value


The property value of     object has changed, but the HashCode of the object has not changed - it operates on the same object

    class Program
    {
        static void Main(string[] args)
        {
            Student outterStu = new Student() { Name = "Tim" };
            Console.WriteLine("HashCode={0},Name={1}", outterStu.GetHashCode(), outterStu.Name);
            Console.WriteLine("======================================");
            SomeSideEffect(ref outterStu);
            Console.WriteLine("HashCode={0},Name={1}", outterStu.GetHashCode(), outterStu.Name);
        }

        static void SomeSideEffect(ref Student stu)
        {
            stu.Name = "Tom";
            Console.WriteLine("HashCode={0},Name={1}",stu.GetHashCode(),stu.Name);
        }
    }

    class Student
    {
        public string Name { get; set; }
    }

Notes:
                           .
                                 .
                              .

3, Output parameter

1. Output parameter → value type

① Call method with output parameters

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Please input first number:");
            string arg1 = Console.ReadLine();
            double x = 0;
            bool b1 = double.TryParse(arg1, out x);
            if (b1 == false)
            {
                Console.WriteLine("input error");
                return;
            }

            Console.WriteLine("Please input second number:");
            string arg2 = Console.ReadLine();
            double y = 0;
            bool b2 = double.TryParse(arg2, out y);
            if (b2 == false)
            {
                Console.WriteLine("input error");
                return;
            }

            double z = x + y;
            Console.WriteLine("{0}+{1}={2}",x,y,z);
        }
    }  

② Declare methods with output parameters

    class Program
    {
        static void Main(string[] args)
        {
            double x = 110;
            bool b = DoubleParser.TryParse("abd", out x);
            if (b == true)
            {
                Console.WriteLine(x + 1);
            }
            else
            {
                Console.WriteLine(x);
            }
        }
    }


    class DoubleParser
    {
        public static bool TryParse(string input, out double result)
        {
            try
            {
                result = double.Parse(input);//Assign values to output parameters in the method body
                return true;
            }
            catch (Exception)
            {
                result = 0;
                return false;
            }
        }
    }

2. Output parameter → reference type

    class Program
    {
        static void Main(string[] args)
        {
            Student stu = null;
            bool b = StudentFactory.Create("Tim", 34, out stu);
            if (b == true)
            {
                Console.WriteLine("Student {0},age is {1}", stu.Name, stu.Age);
            }
        }
    }


    class Student
    {
        public int Age { get; set; }
        public string Name { get; set; }
    }

    class StudentFactory
    {
        public static bool Create(string stuName, int stuAge, out Student result)
        {
            result = null;
            if (string.IsNullOrEmpty(stuName))
            {
                return false;
            }

            if (stuAge < 20 && stuAge > 80)
            {
                return false;
            }

            result = new Student() { Name = stuName, Age = stuAge };
            return true;
        }
    }

4, Array parameters

Notes:
                         .

1. Before using params keyword

    class Program
    {
        static void Main(string[] args)
        {
            //Declaration array
            int[] myintArray = new int[] { 1, 2, 3 };

            int result = CalculateSum(myintArray);
            Console.WriteLine(result);
        }

        //Calculates the sum of all elements in an integer array
        static int CalculateSum(int[] intArray)
        {
            int sum = 0;
            foreach (var item in intArray)
            {
                sum += item;
            }
            return sum;
        }
    }

2. After using params, you no longer need to declare the array separately

    class Program
    {
        static void Main(string[] args)
        {
            ////Declare array
            //int[] myintArray = new int[] { 1, 2, 3 };

            int result = CalculateSum(1,2,3);//No longer need to declare arrays separately
            Console.WriteLine(result);//6
        }

        //Calculates the sum of all elements in an integer array
        static int CalculateSum(params int[] intArray)
        {
            int sum = 0;
            foreach (var item in intArray)
            {
                sum += item;
            }
            return sum;
        }
    }


5, Named parameter

1. Unnamed call example

    class Program
    {
        static void Main(string[] args)
        {
	        // Call without name
            PrintInfo("Tim", 34);//name of string type; age of int type
        }

        static void PrintInfo(string name, int age)
        {
            Console.WriteLine("Hello {0},you are {1}.",name,age);
        }            
    }

2. Named call example

Named parameter: parameter position is not constrained by parameter list order
Improve code readability

    class Program
    {
        static void Main(string[] args)
        {
            //Named invocation
            PrintInfo(age: 34, name: "Tim");//Parameter position is not constrained by parameter list order
        }

        static void PrintInfo(string name, int age)
        {
            Console.WriteLine("Hello {0},you are {1}.",name,age);
        }            
    }

6, Optional parameters

Parameter is "optional" because it has a default value

    class Program
    {
        static void Main(string[] args)
        {
            //Optional parameters
            PrintInfo();//Hello Tim,you are 34.
        }

        static void PrintInfo(string name = "Tim", int age = 34)
        {
            Console.WriteLine("Hello {0},you are {1}.", name, age);
        }
    }

7, Extension method (this parameter)

1. No extension method example

    class Program
    {
        static void Main(string[] args)
        {
            double x = 3.14159;
            double y = Math.Round(x, 4);//There is no Round method for double type, only Math.Round can be used
            Console.WriteLine(y);            
        }      
    }

2. There are examples of extension methods

    class Program
    {
        static void Main(string[] args)
        {
            double x = 3.14159;
            double y = x.Round(4);//Call extension method Round
            Console.WriteLine(y);            
        }      
    }

    static class DoubleExtension
    {
        public static double Round(this double input, int digits)
        {
            double result = Math.Round(input, digits);
            return result;            
        }
    }

3.LINQ method example

Determine whether all elements in the set are greater than 10
① LINQ extension method not used

    class Program
    {
        static void Main(string[] args)
        {
            List<int> myList = new List<int>() { 11, 12, 13, 14, 15 };
            bool result = AllGreaterThanTen(myList);
            Console.WriteLine(result);
        }

        //Determine whether all elements in the set are greater than 10
        static bool AllGreaterThanTen(List<int> intList)
        {
            foreach (var item in intList)
            {
                if (item<=10)
                {
                    return false;
                }
            }
            return true;
        }   
    }

② Using LINQ extension method

    class Program
    {
        static void Main(string[] args)
        {
            List<int> myList = new List<int>() { 11, 12, 13, 14, 15 };
            bool result = myList.All(i => i > 10);//Use the extension method All() to determine that all elements in the collection are greater than 10
            Console.WriteLine(result);
        }
    } 

Eight, summary

52 original articles published, 84 praised, 20000 visitors+
Private letter follow

Tags: Programming

Posted on Sun, 15 Mar 2020 03:18:53 -0400 by Maugrim_The_Reaper