-1

Consider the following code snippet:

public class Foo
{
   public int ID { get; set; }
   public string FirstName { get; set; }
   ...

   public Foo(int Id, string firstName)
   {
      ID = Id;
      FirstName = firstName;
   }
}

Assuming we have a method which takes in Foo object as a parameter. I can create the object as follows:

var first = new Foo { ID = 1, FirstName = "Test"};
var second = new Foo(1, "Test");

Then pass to the method which is accepting the object as a parameter. My actual classes consist of 10+ properties, I simplified it for the question.

My question is, is there a difference here or both doing the same thing? or it's more a case of preference.

Thanks in advance for your help.

Izzy
  • 6,740
  • 7
  • 40
  • 84
  • You should only pass (for the rest of the life time) immutable values as parameters to the constructor or a 'must have a valid value on construction' values. The rest are mutable properties. – Jeroen van Langen Nov 20 '18 at 13:56
  • You actually asking what are the differences between those two object initializations...and the title is about passing object to method. This is misleading. Rephrasing your question would lead you to answer like [here](https://codereview.stackexchange.com/questions/4325/styles-object-initializer-vs-constructor-object-creation) – Renatas M. Nov 20 '18 at 14:01
  • You cant actually use the "first" initialization using the class posted. (as it does not have an empty ctor) – Magnus Nov 20 '18 at 14:05

1 Answers1

0

I think that the big difference here is that you can force the the user of Foo to provide certain values when instantiating Foo by making a constructor which takes those parameters. Other than that it's preference.

Mark Reimer
  • 116
  • 4
  • not really, by being able to do this var first = new Foo { ID = 1, FirstName = "Test"}; it means that there already is a constructor with no parameters meaning that the user is not forced to provide values when instantiating Foo – Sergiu Muresan Nov 20 '18 at 13:59