C # value type and reference type parameter [basic]

Source: Internet
Author: User

 

According to the parameter type and transmission mode, there are four different situations:
Value Type parameter passing by value; (INT m)

Pass the reference type parameter by value (address value); (string Str)


Value Type parameter passed by reference; (ref int m)


Transmit parameters of the reference type by reference; (ref string Str)

 

Parameter of value type and reference type

Class Demo
{
Static   Void Main ( String [] ARGs)
{
Int N =   100 ;
String Str =   " One " ;

Changebyvalue ( Ref N ); // Value Type: ref transmits the address of Variable N (that is, the address of value type)
Changebyref ( Ref Str ); // Reference Type: ref transmits the STR address (that is, the reference) of the variable)

Console. writeline (N );
Console. writeline (STR );
}
Private   Static   Void Changebyvalue ( Ref   Int M)
{
M
=   200 ; // Actually, it changes the value of Variable N.
}
Private   Static   Void Changebyref ( Ref   String S)
{
S
=   " Two " ;
}

// Through, the parameter with ref (or out), and the method without REF (or out) can be overloaded.
Private   Static   Void Changebyref ( String S)
{
S
=   " Two " ;
}

//Error: you cannot define a different overload method on ref and out.
//Cause: In msil, ref and out are of the same type.
/*Private Static void changebyref (out string S)
{
S = "two ";
}
*/ 
}

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.