What is the difference between a reference type and value type in c#?

后端 未结 14 2452
谎友^
谎友^ 2020-11-21 05:13

Some guy asked me this question couple of months ago and I couldn\'t explain it in detail. What is the difference between a reference type and a value type in C#?

I

相关标签:
14条回答
  • 2020-11-21 06:02

    value data type and reference data type

    1) value( contain the data directly ) but reference ( refers to the data )

    2) in value( every variable has its own copy) but
    in reference (more than variable can refer to some objects)

    3) in value (operation variable can`t effect on other variable ) but in reference (variable can affect other )

    4) value types are(int, bool, float) but reference type are (array , class objects , string )

    0 讨论(0)
  • 2020-11-21 06:03

    Your examples are a little odd because while int, bool and float are specific types, interfaces and delegates are kinds of type - just like struct and enum are kinds of value types.

    I've written an explanation of reference types and value types in this article. I'd be happy to expand on any bits which you find confusing.

    The "TL;DR" version is to think of what the value of a variable/expression of a particular type is. For a value type, the value is the information itself. For a reference type, the value is a reference which may be null or may be a way of navigating to an object containing the information.

    For example, think of a variable as like a piece of paper. It could have the value "5" or "false" written on it, but it couldn't have my house... it would have to have directions to my house. Those directions are the equivalent of a reference. In particular, two people could have different pieces of paper containing the same directions to my house - and if one person followed those directions and painted my house red, then the second person would see that change too. If they both just had separate pictures of my house on the paper, then one person colouring their paper wouldn't change the other person's paper at all.

    0 讨论(0)
提交回复
热议问题