Break, Continue, ReadOnly, Const, Ref, and Out params, readonlyparams

Source: Internet
Author: User

Break, Continue, ReadOnly, Const, Ref, and Out params, readonlyparams

I have studied basic things such as Break and Continue; ReadOnly and Const; ref, out, And params, but I have not carefully studied what the problem is. I recently used it in development, let's make a summary:

1. Break and Continue

// Break jumps out of the entire loop body and does not execute this loop. continue ends a single loop and continues the next loop. // For more information, contact QQ 931697811 (yeyu Wutong)

1 # region Break Test 2 3 Console. writeLine ("========= Break ======"); 4 int x = 0; 5 while (x ++ <20) 6 {7 if (x = 3) 8 {9 break; 10} 11 Console. writeLine ("{0} \ n", x); 12} 13 # endregion
View Code

 

1 # region Continue Test 2 Console. writeLine ("========= Continue ========"); 3 int k = 0; 4 while (k ++ <10) 5 {6 if (k = 3) 7 {8 continue; 9} 10 Console. writeLine ("{0} \ n", k); 11} 12 # endregion
View Code

2. ReadOnly and Const

// If you have any questions, contact QQ 931697811

1. const-modified constants must be initialized during Declaration; readonly-modified constants can be delayed until the constructor is initialized.

2. const-modified constants are parsed during compilation, that is, the constant value is replaced with the initial value. readonly-modified constants are delayed until running.

3. In addition, the const constant can be declared in the class or in the function body, but the static readonly constant can only be declared in the class.

1 # region ReadOnly 2 static readonly int A = B * 10; 3 static readonly int B = 10; 4 5 const int j = k * 10; 6 const int k = 10; 7 8 static void Main (string [] args) 9 {10 Console. writeLine ("=== Readonly output value is: ="); 11 Console. writeLine ("A is {0 }. B is {1} ", A, B); 12 Console. writeLine ("= Const output value is: ="); 13 Console. writeLine ("j is {0 }. k is {1} ", j, k); 14 Console. readKey (); 15} 16 # endregion
View Code

3. ref and out, params

Question:

Now we need to exchange the values of the two variables a and B through a method called Swap. A = 1, B = 2 before switching, asserted: After switching a = 2, B = 1

 

The encoding is as follows:

1 1 class Program 2 2 {3 3 static void Main (string [] args) 4 4 {5 5 int a = 1; 6 6 int B = 2; 7 7 Console. writeLine ("before switching \ ta = {0} \ tb = {1} \ t", a, B); 8 8 Swap (a, B); 9 9 Console. writeLine ("after switching \ ta = {0} \ tb = {1} \ t", a, B); 10 10 Console. read (); 11 11} 12 12 // exchange the values of two variables a and B 13 private static void Swap (int a, int B) 14 14 {15 15 int temp = a; 16 16 a = B; 17 17 B = temp; 18 18 Console. writeLine ("Method \ ta = {0} \ tb = {1} \ t", a, B); 19 19} 20}
View Code

Running result:

Exchange before a = 1 B = 2

Method a = 2 B = 1

After the switch, a = 1 B = 2

Not meeting our needs!

Cause Analysis: int type is a value type, which exists in the thread stack. When the Swap (a, B) method is called, it is equivalent to copying the values of a and B (I .e., 1 and 2), and then exchanging the two values in the method. After the exchange, a is still the original a, B is the original B. This is the principle of passing values in C #. It transfers a copy of the data corresponding to the variable instead of a reference.

 

Modify the Code as follows to achieve the desired result:

1 class Program 2 2 {3 3 static void Main (string [] args) 4 4 {5 5 int a = 1; 6 6 int B = 2; 7 7 Console. writeLine ("before switching \ ta = {0} \ tb = {1} \ t", a, B); 8 8 Swap (ref a, ref B ); 9 9 Console. writeLine ("after switching \ ta = {0} \ tb = {1} \ t", a, B); 10 10 Console. read (); 11 11} 12 12 // exchange the values of two variables a and B 13 private static void Swap (ref int a, ref int B) 14 14 {15 15 int temp = a; 16 16 a = B; 17 17 B = temp; 18 18 Console. writeLine ("Method \ ta = {0} \ tb = {1} \ t", a, B); 19 19} 20}
View Code

1. About heavy load

Principle: methods with the out | ref keyword can be overloaded with methods without the out and ref keywords. to overload the out and ref keywords, the compiler will prompt: you cannot define method overloading only on ref and out.

2. Initial values before a call

Principle: Before calling a function as a parameter, the ref parameter must be assigned an initial value. Otherwise, the compiler will prompt that the unassigned local variable is used;

Before calling an out function as a parameter, the real parameter can not be assigned an initial value.

3. Questions about initial parameter values introduced in the function

Principle: In the called function, the out parameter is assigned a value at least once before the return value. Otherwise, the compiler will prompt that the out parameter is not assigned a value;

In the called function, parameters introduced by ref do not need to be assigned an initial value before return.

Summary:In C #, ref and out provide a solution for passing value types by reference. Of course, the reference types can also be modified using ref and out, but this has no meaning. Because the reference data type is a copy of the passed reference rather than a value. The ref and out keywords tell the compiler that the parameter address is passed instead of the parameter itself, which is the same as the default transfer method of the reference type. At the same time, the compiler does not allow overload between the out and the ref. It also fully demonstrates that the difference between the out and the ref is only from the compiler's perspective, and the IL code they generate is the same. Some may wonder why the value type will not allocate memory in the managed heap. why can it be passed by address? Although the value type lives in the thread stack, it represents the data itself (unlike the referenced data type itself, it does not represent the data but points to a memory reference ), however, the value type also has its own address, that is, the pointer. After modifying it with ref and out, the pointer is passed. Therefore, after, the value of B is truly exchanged. This is the benefit of ref and out.

For more information, such as This and Base, please share it later.

 


What are the similarities and differences between const and readonly?

The concept of const is a variable that contains unchangeable values.
Constant expressions are fully computed during compilation. Therefore, constants cannot be initialized by extracting values from a variable.
If const int a = B + 1; B is a variable, it is obvious that the result cannot be calculated during compilation, so constants cannot be initialized using variables.

Readonly allows a field to be set as a constant, but some operations can be performed to determine its initial value.
Because readonly is executed during computing, of course it can be initialized with some variables.
Readonly is an instance Member, so different instances can have different constant values, which makes readonly more flexible.

The readonly keyword is different from the const keyword.

1. the const field can only be initialized in the declaration of this field.
The readonly field can be initialized in the Declaration or constructor. Therefore, the readonly field may have different values based on the constructors used.
2. the const field is the number of compiling times, while the readonly field can be used for running times.
3. const is static by default, and readonly must display the declaration if it is set to static.
4. For constants of the reference type, the possible values of const can only be string and null.
Readonly can be of any type

* You need to pay attention to the following issues:

For a readonly Reference type, the value assignment (write) operation is not allowed. The read and write operations on its members are still unrestricted.

Public static readonly Class1 my = new Class1 ();
...
My. SomeProperty = 10; // normal
My = new Class1 (); // error. The object is read-only.

However, if the Class1 in the above example is not a Class but a struct, then the following two statements will go wrong.

Static readonly:

In Java, static is executed once when a class is loaded.

C. It is strange that almost every java book will talk about the static problem. C # often only describes how to use it, but it should be initialized before the main function is called, so static readonly is also running, and can be used to pay the value, such:

Private static readonly string path = System. Windows. Forms. Application. StartupPath + "aaa ";

In c #, const is different from readonly.

The concept of const is a variable that contains unchangeable values.
Constant expressions are fully computed during compilation. Therefore, constants cannot be initialized by extracting values from a variable.
If const int a = B + 1; B is a variable, it is obvious that the result cannot be calculated during compilation, so constants cannot be initialized using variables.

Readonly allows a field to be set as a constant, but some operations can be performed to determine its initial value.
Because readonly is executed during computing, of course it can be initialized with some variables.
Readonly is an instance Member, so different instances can have different constant values, which makes readonly more flexible.

The readonly keyword is different from the const keyword.

1. the const field can only be initialized in the declaration of this field.
The readonly field can be initialized in the Declaration or constructor. Therefore, the readonly field may have different values based on the constructors used.
2. the const field is the number of compiling times, while the readonly field can be used for running times.
3. const is static by default, and readonly must display the declaration if it is set to static.
4. For constants of the reference type, the possible values of const can only be string and null.
Readonly can be of any type

Summary
Const can only be initialized with constants at the initial stage. For each compiled result, the const value is fixed, while the readonly value can be determined during running ~~

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.