Why the object is not updated as NULL

When I update my objhow null, its output is 30, but not an exception, but when I update obj.Age = 25, the result is 25.

I donโ€™t understand what is going on behind the scenes. Can someone explain why this is happening?

public class A
{
    public int age;
}

class Program
{
    public static void Test(A obj)
    {
        //obj = null;
        //obj.age = 25;
    }

    static void Main(string[] args)
    {
        try
        {
            A obj = new A();
            obj.age = 30;
            Test(obj);
            Console.WriteLine(obj.age);
        }
        catch (Exception)
        {
            throw;
        }
    }
}
+4
source share
2 answers

Pay attention to the signature of the method -

public static void Test(A obj)

The parameter is not passed as ref. When reference types are passed as a parameter, without specifying how ref. You can change the values โ€‹โ€‹of properties inside an object, but you cannot assign an object to point it to another memory location.

In simple words you cannot do - obj = nullOR obj = new A()ORobj = instanceOfAnotherObject

, obj ref -

public static void Test(ref A obj)
+2

obj = null;, null, null. Test, , obj Main, obj null Test .
/, , Test ref

public static void Test(ref A obj)

Test

...
A obj = new A();
obj.age = 30;
Test(ref obj);
...  

obj Main.


obj.age = 25; Test (, obj null), , obj Main, age 25.
, - A, . int , Test Main, .

+2

Source: https://habr.com/ru/post/1649666/


All Articles