user1005793
user1005793

Reputation: 2911

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();
}

Upvotes: 0

Views: 177

Answers (2)

Ali pishkari
Ali pishkari

Reputation: 542

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

Upvotes: 0

Rob
Rob

Reputation: 27357

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.

Upvotes: 1

Related Questions