logo
CSharp_Prog_Guide

Пример результатов выполнения.

Please select the convertor

1. From Celsius to Fahrenheit.

2. From Fahrenheit to Celsius.

:2

Please enter the Fahrenheit temperature: 98.6

Temperature in Celsius: 37.00

Дополнительные примеры результатов могут выглядеть следующим образом.

Please select the convertor

1. From Celsius to Fahrenheit.

2. From Fahrenheit to Celsius.

:1

Please enter the Celsius temperature: 37.00

Temperature in Fahrenheit: 98.60

How to: Know the Difference Between Passing a Struct and Passing a Class Reference to a Method

This example shows that when a struct is passed to a method, a copy of the struct is passed, but when a class instance is passed, a reference is passed.

The output of the following example shows that only the value of the class field is changed when the class instance is passed to the ClassTaker method. The struct field, however, does not change by passing its instance to the StructTaker method. This is because a copy of the struct is passed to the StructTaker method, while a reference to the class is passed to the ClassTaker method.

Example

class TheClass

{

public string willIChange;

}

struct TheStruct

{

public string willIChange;

}

class TestClassAndStruct

{

static void ClassTaker(TheClass c)

{

c.willIChange = "Changed";

}

static void StructTaker(TheStruct s)

{

s.willIChange = "Changed";

}

static void Main()

{

TheClass testClass = new TheClass();

TheStruct testStruct = new TheStruct();

testClass.willIChange = "Not Changed";

testStruct.willIChange = "Not Changed";

ClassTaker(testClass);

StructTaker(testStruct);

System.Console.WriteLine("Class field = {0}", testClass.willIChange);

System.Console.WriteLine("Struct field = {0}", testStruct.willIChange);

}

}

Class field = Changed

Struct field = Not Changed