C # Type Link Properties?

I start with C # and I have a question.

Let's say I have an object:

Person

and the Person property called Cat:

Person.Cat

If I do this:

Cat cat = new Cat(stuff);
cat.Name = "Alan";
Person.Cat = cat;

Is Cat a direct link to a cat? If I do this:

Person.Cat.Name = "John";

Will the cat's name be "John"?

Because I think I did something similar before, and I had a NullReferenceException or something like that.

+3
source share
3 answers

If "cat" is a class, that is, a reference type, then a copy of this link will be saved in person. This means that the changes made to the properties of the cat will be reflected personally. However, since this is a copy of the original link, the behavior looks like this:

Cat cat = new Cat(stuff);
cat.Name = "Alan";
Person.Cat = cat;
cat.Name = "Will";  //Person.Cat.Name is now "Will"
cat = new Cat(stuff);
cat.Name = "Greg";  
// Person.Cat is still named "Will".  
// The original reference now points  to a different object on the heap than does Person.Cat.

Cat , , (, , ).

+5

, :

// Person class.
public class Person {

    // Automatic property.
    public Cat Cat { get; set; }

}

// Cat class (not a struct!).
public class Cat {

    // Automatic property.
    public string Name { get; set; }

}

myPerson.Cat . , , , Cat, , .

, myPerson.Cat null. Cat, null. - null myPerson.Cat.Name, NullReferenceException.

, , null if (myPerson.Cat != null) { ... } . , , null, . , , , .

+1

Cat cat?

. :

var cat = new Cat(stuff);
cat.Name = "Alan";
Person.Cat = cat;
cat.Name = "George";
var nowCalledGeorge = Person.Cat.Name;

,

""?

- .

0

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


All Articles