Câu hỏi phỏng vấn C#
Câu hỏi

How to solve Cir...

Câu trả lời

Here is how to solve circular references in C#:

Circular References in C#

A circular reference occurs when two or more objects reference each other, creating a circular dependency. This can happen when you have a bidirectional relationship between classes. For example:

csharp Copy
public class Person
{
    public string Name { get; set; }
    public Company Company { get; set; }
}

public class Company 
{
    public string Name { get; set; }
    public Person Owner { get; set; }
}

In this example, Person has a Company property and Company has a Person property, creating a circular reference.

How to Solve Circular References

There are a few ways to solve circular references in C#:

1. Use Lazy Loading

You can use lazy loading to only load the referenced object when it is actually needed. This avoids the circular reference issue. For example:

csharp Copy
public class Person
{
    private Lazy<Company> _company;
    public string Name { get; set; }
    public Company Company => _company.Value;

    public Person(string name)
    {
        Name = name;
        _company = new Lazy<Company>(() => new Company(this));
    }
}

public c...
senior

senior

Gợi ý câu hỏi phỏng vấn

middle

What is a Destructor in C# and when shall I create one?

expert

in C#, when should we use abstract classes instead of interfaces with extension methods?

middle

How can you prevent a class from overriding in C#?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào