mishap
mishap

Reputation: 8525

C# passing parameters by reference confusion

After reading some articles still confused. Why changing the value of the StringBuilder would change and value of DateTime doesn't ? Both are reference types as I understand:

class Program
{
    static void Main(string[] args)
    {
        DateTime myDt = DateTime.MinValue;
        Change(myDt);
        Console.WriteLine(myDt);

        StringBuilder y = new StringBuilder();
        y.Append("hello");
        Foo(y);
        Console.WriteLine(y);

        String test = "hello";
        Foo(test);

    }

    public static void Change(DateTime dt)
    {
       dt.AddDays(24); 
       //or dt=dt.AddDays(24);
    }

    static void Foo(StringBuilder x)
    {
        x.Append(" world");
    }

    static void Foo(String x)
    {
        x = x + " world";
    }
}

Upvotes: 0

Views: 179

Answers (5)

BoltClock
BoltClock

Reputation: 724542

DateTime is a value type (a struct) that cannot be modified. It is not a reference type.

When you call a method that appears to change a struct, it often really returns a brand new struct, without modifying the original because the original cannot be modified (it is immutable). Although the same applies to strings, strings aren't value types; they're reference types which have been designed to be immutable, hence the need for classes such as StringBuilder.

Also, passing reference types as parameters is not the same as passing parameters by reference using ref or out.

Upvotes: 5

EtherDragon
EtherDragon

Reputation: 2698

As others mentioned the difference is in a Class (which StringBuilder is) and a Struct (which DateTime is). Here are some articles to further help:

http://msdn.microsoft.com/en-us/library/ms173109.aspx

and

http://msdn.microsoft.com/en-us/library/aa288471(v=vs.71).aspx

A good understanding of structs versus classes is important in OOP, and particularly c#

Upvotes: 0

DaveShaw
DaveShaw

Reputation: 52818

A DateTime is a struct - hence a value type. Strings are immutable reference types.

Upvotes: 1

Tigran
Tigran

Reputation: 62265

DateTime is a structure, so it's a value type.

So like any other value type it's past by value (copied in practise) and only after injected into the function stack.

Upvotes: 3

Yuriy Faktorovich
Yuriy Faktorovich

Reputation: 68747

DateTime isn't a reference type, it's a structure, which means a value type.

Upvotes: 11

Related Questions