简体   繁体   中英

Is it a good approach to call a method on a constructor in C#?

I've noticed that I've been doing this a lot (mostly because all my methods are non-static):

var person = new Person();
var addresses = person.GetAddresses();

A lot of times I just need to call the method once inside my other method. I noticed I can just do this instead:

var addresses = new Person().GetAddresses();

Is there any problems doing it that way? It seems like a lot less typing for me. For example, if I wanted to load a model with addresses, I can just do:

public ActionResult HelloWorld() {
    var model = new MyModel { Addresses = new Person().GetAddresses() };
    return View(model);
}

What do you guys think?

Btw, my methods are non-static because I'm using a repository. My class is setup something like this:

private IMyRepository _myRepository = new MyRepository();

Person () {
    // initialize properties
}

// Constructor for unit testing...
Person (IMyRepository repository) : this() {
   _myRepository = repository;
}

public GetAddresses() {
    return _myRepository.GetAddresses();
}

It's fine to do that, it won't cause any problems. Though it is questionable to have a class that's immediately thrown away. Maybe GetAddresses should be static?

But in any case, it's perfectly fine to do.

it's ok to do that, but if you want to some jobs just after creating an object of person, you can create an event and raise it in your constructor , then you have your object and some custom data in your own event args in your main class. if it is helpful I can send you a sample code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM