Home > Enterprise >  Why does the below code not returning the expected output in C#?
Why does the below code not returning the expected output in C#?

Time:04-07

I want to make the object null using a static method. For explanation, I have created a sample code -

class Program
{
    static void Main(string[] args)
    {
        Car car = new Car();
        car.Name = "Audi";
        makeNull(car);
        Console.WriteLine(car.Name);

        Console.ReadKey();
    }

    static void makeNull(Car c)
    {
        c = null;
    }
}

class Car
{
    public string Name;
}

//Output - Audi

I was expecting a Null Exception for the above code but surprisingly got "Audi" as output. Can anyone explain why exactly it is behaving like this ?

CodePudding user response:

You cannot manipulate the reference itself, without declaring it as ref. Thus this should work:

static void MakeNull(ref Car c)
{
    c = null;
}

MakeNull(ref car);

Note that you can modify the data the reference points to, so this would give the output "VW":

static void MakeNull(Car c)
{
    c.Name = "VW";
}
  • Related