Value Types and Reference Types (C#)

C# structs are derived from System.ValueType which overrides the virtual methods in System.Object to use value-based semanitcs instead of reference-based ones.

System.ValueType is allocated on stack rather than on garbage-collected heap. Its lifetime is in the defining scope. Once it runs out of the defining scope, it is popped off the stack. Game over!

int type is a System.Int32 structure.

By default, when a value type contains other reference types (e.g. a struct contains a class), assignment results in a copy of the references (shallow copy).

If a reference type is passed by reference (using ref, the reference is copied by reference), the called method may change the values of the state data and the object it is referencing (i.e. reassign it to a different or new object). 

But if a reference type is passed by value (without modifier, the reference is copied by value), its state value could be changed but not the object being referenced (meaning it is still pointing to the same object on heap).

namespace ConsoleApp11
{
    public class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public Person(string name, int age)
        {
            Name = name; 
            Age = age;
        }
        public void Display()
        {
            Console.WriteLine($"{Name} {Age}"); 
        }
    }
}

namespace ConsoleApp11
{
    public static class Common
    {
        public static void ChangePerson(ref Person p)
        {
            p.Age = 100;
            p = new Person("Cici", 25);
        }

        public static void ChangePerson(Person p)
        {
            p.Age = 99;
            p = new Person("Lily", 35);
        }
    }
}
using ConsoleApp11;
using static ConsoleApp11.Common;

Person p1 = new Person("Mike", 80);
Console.WriteLine("Original person");
p1.Display();
ChangePerson(p1);
Console.WriteLine("After being passed by value");
p1.Display();
ChangePerson(ref p1);
Console.WriteLine("After being passed by reference");
p1.Display();
Console.ReadLine();

// result:
// Original person
// Mike 80
// After being passed by value
// Mike 99
// After being passed by reference
// Cici 25

 Both value types and reference types can implement interfaces, support fields, method, overloaded operators, constants, properties, and events.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值