C# Study Note: Values and References

1.   Reference Type VS Value Type

Most primitive types such as int, float, double, char…(NOT string) are value types.

When you declare a value type variable, the compiler generate codes to allocate a block of memory for the variable.

Class types are a big part of reference types.

When you declare a class type variable, the compiler does not allocate memory for the actual content. Instead, it allocates a small piece of memory to hold a reference(address) to the actual content.

The memory of the actual content is allocated only when the new keyword is called to create this object.

For example:

int i = 42;

int ii = i;

++i;

You can see that i becomes 43 and ii is 42, because i and ii are in different memory space.

Another example:

Circle c = new Circle(42);

Circle rc = c;

rc.setRadius(46);

c.getRadius();

rc.getRadius();

Now you can see the radius of both Circle variable is 46, because both variable refers to the same Circle object in memory.

2.   null values and Nullable types

When you declare a variable of reference type and don’t initialize it, the variable has the value null.

You can also assign null to any variable of reference type. This means the variable doesn’t refer to any class entity.

Note: if you explicitly declare a reference variable as null, chances are that the garbage collector will become more actively recycle the resource it used to refer to.

The null value is useful for initializing reference types. Sometimes, you need an equivalent value for value types, but null is itself a reference, and so you cannot assign it to a value type. The following statement is therefore illegal in C#:

int k = null; //illegal

However, C# defines a modifier that you can use to declare that a variable is a nullable value type. A nullable value type behaves in a similar manner to the original value type, but you can assign the null value to it. You use the question mark (?) to indicate that a value type is nullable, like this:

int? k = null;

You can make certain whether a nullable variable contains null by testing it in the same way as a reference type.

if (i==null) {/* …… */}

You can assign an expression of the appropriate value type directly to a nullable variable. The following examples are all legal:

int? j = null;

int k = 99;

j = k;

j = 100;

However, the converse is NOT true. You cannot assign a nullable variable to an ordinary value type variable. So, given the definitions of variables j and k from the preceding example, the following statement is not allowed:

k=j;

This also means that you cannot use a nullable variable as a parameter to a method that expects an ordinary value type.

int? m = 1;

func(m);

3.   ref and out parameters

Generally, when you pass an argument to a method, the corresponding parameter is initialized by a copy of the argument, regardless of whether it is value type or reference type or nullable type.

In some cases, you want to affect the actual argument when calling the method. In this time, a ref parameter is in handy.

void swap(int a, int b)

{

int temp = a;

a = b;

b = temp;

} // this code is of no use

void swap(ref int a, ref int b)

{

int temp = a;

a = b;

b = temp;

} // useful

Remember that C# ensures the rule that a variable must be initialized before it can be used. This rule also applies for parameters, including ref parameters. The code below won’t compile according to this rule.

public static void Main(string[] args)

{

int a, b;

swap (a, b);

}

However, there might be times when you want the method itself to initialize the parameter. You can do this with the out keyword.

The out keyword is syntactically similar to the ref keyword.

The keyword out is short for output. When you pass an out parameter to a method, the method MUST assign a value to it before it finishes or returns.

Example code:

static void doInitialize(out int param)

{

param = 42;

}

static void Main()

{

int arg; // not initialized

doInitialize(out arg); // legal

Console.WriteLine(arg); // writes 42

}

4.   Boxing and Unboxing mechanism

Boxing means converting value type to reference type, while Unboxing means recover the value type from a reference type.

An example of boxing and unboxing:

int n = 15;

object N = n;

int _n = (int)N; //_n==42

What happens behind the code?

Remember that i is a value type and that it lives on the stack. If the reference inside o referred directly to i, the reference would refer to the stack. However, all references must refer to objects on the heap; creating references to items on the stack could seriously compromise the robustness of the runtime and create a potential security flaw, so it is not allowed. Therefore, the runtime allocates a piece of memory from the heap, copies the value of integer i to this piece of memory, and then refers the object o to this copy.

On the other hand, if o does not refer to a boxed int, there is a type mismatch, causing the cast to fail , in which case an InvalidCastException will be thrown. Eg:

Circle c = new Circle(42);

object o = c; // doesn‘t box because Circle is a reference variable

int i = (int)o; // compiles okay but throws an exception at run time

Keep in mind that boxing and unboxing are expensive operations because of the amount of checking required and the need to allocate additional heap memory. Boxing has its uses, but injudicious use can severely impair the performance of a program.

5.   Casting data safely: Introducing is and as operators

By using a cast, you can specify that, in your opinion, the data referenced by a System.object has a specific type and that it is safe to reference the object by using that type. The C# compiler will not check that this is the case, but the runtime will. If the type of object in memory does not match the cast, the runtime will throw an InvalidCastException.

WrappedInt wi = new WrappedInt();

...

object o = wi;

if (o is WrappedInt)

{

WrappedInt temp = (WrappedInt)o;

// This is safe; o is a WrappedInt

...

}

WrappedInt wi = new WrappedInt();

...

object o = wi;

WrappedInt temp = o as WrappedInt;

if (temp != null)

{

... // Cast was successful

}

The is operator takes two operands: a
reference to an object on the left ,and the name of a type on the right. If the
type of the object referenced on the heap has the specified type, is evaluates to
true; otherwise, is evaluates to false.

The as operator takes an object and a
type as its operands. The runtime attempts to cast the object to the specified type.
If the cast is successful, the result is returned . If the cast is unsuccessful,
the as operator evaluates to the null value and assigns that to temp instead.

时间: 2024-10-27 00:33:13

C# Study Note: Values and References的相关文章

My Study Note of JDBC (1)

# JDBC -- The Java™ Tutorials # Study Note of JDBC# victor# 2016.05.31 JDBC Study Note ----connect to database 通常,使用JDBC执行SQL语句需要下面5 个步骤:1> 建立一个连接         | establish a connection2> 构造一条语句         | create a statement3> 执行语句             | execute

C++ Primer Study Note 系列[1]-chapter1快速入门

I want to study it all the time , and now I am ready to study this book in the next mouth. Time : 2014/07/02 先看一个程序体验一下: #include <iostream> int main() {     /*This is a test example*/     std::cout << "Enter two numbers:" << s

CoderPig’s Android Study Note——目录

CoderPig's Android Study Note--目录 前言 雏形,有时间慢慢完善,内容也是,有时间就写- 一.概念与开发辅助工具 1)概念性的东西 1.1 背景相关与系统架构 2)开发辅助工具 1.2.1 APK反编译工具之:apktool + dex2jar + jd-gui 1.2.1 APK反编译工具之:jadx 1.2.2 网络抓包工具之:Charles 1.2.2 网络抓包工具之:Fiddler 3)网页工具/插件 1.3.1 XML布局代码自动生成findViewByI

HotSpot JVM and GC basics study note

Hotspot JVM and GC basics study note JVM components HotSpot JVM comprises three main components: the class loader, the runtime data areas and the execution engine. Key JVM components There are three key components related to tune performance: the hea

My Study Note of JDBC (2.1)

# JDBC -- The Java™ Tutorials # Study Note of JDBC# victor# 2016.05.31 JDBC Study Note ----connect to database 通常,使用JDBC执行SQL语句需要下面5 个步骤:1> 建立一个连接         | establish a connection2> 构造一条语句         | create a statement3> 执行语句             | execute

CCJ PRML Study Note - Chapter 1.2 : Probability Theory

Chapter 1.2 : Probability Theory Chapter 1.2 : Probability Theory Christopher M. Bishop, PRML, Chapter 1 Introdcution Chapter 1.2 : Probability Theory 1. Uncertainty 2. Example discussed through this chapter 3. Basic Terminology 3.1 Probability densi

Beginning Scala study note(4) Functional Programming in Scala

1. Functional programming treats computation as the evaluation of mathematical and avoids state and mutable data. Scala encourages an expression-oriented programming(EOP) 1) In expression-oriented programming every statement is an expression. A state

CCJ PRML Study Note - Chapter 1.5 : Decision Theory

Chapter 1.5 : Decision Theory Chapter 1.5 : Decision Theory Christopher M. Bishop, PRML, Chapter 1 Introdcution 1. PRML所需要的三论: Probability theory: provides us with a consistent mathematical framework for quantifying and manipulating uncertainty. Deci

CCJ PRML Study Note - Chapter 1 Summary : MLE (Maximum-likelihood Estimate) and Bayesian Approach

Chapter 1 Summary : MLE (Maximum-likelihood Estimate) and Bayesian Approach Chapter 1 Summary : MLE (Maximum-likelihood Estimate) and Bayesian Approach Christopher M. Bishop, PRML, Chapter 1 Introdcution 1. Notations and Logical Relation Training dat