15

Why can't you call methods with c# object initializer syntax?

It seems to me that the property setters are called in the order that they are set in the syntax, so why not allow calls to methods as well? If there is a good reason, I'm missing it.

EDIT

I realize the semantic differences between methods and properties and the technical similarities. The purpose of this question is to probe for a good technical reason that they did not include the feature.

this. __curious_geek, I hear what you are saying, but I'm sure there are some features they haven't included because it wasn't technically feasable.

That's all I'm after. The overwhelming unwelcoming tone is heard loud and clear. Stackoverflow is no longer a "Question and Answer site" but instead a "Defend your question site".

Edit 2

Sample usage:

var mySuperLongVariableNameThatIDontWantToTypeOverAndOverAgainAndIsntThatTheWholePointAnyway  = new Thingy
    {
        Name = "Marty McFly",
        AddChildren("Biff","Big Bird","Alf"),
        // 1000 other properties and method calls.....
    }
Community
  • 1
  • 1
Ronnie Overby
  • 45,287
  • 73
  • 267
  • 346
  • 7
    If I had to guess why, I'd say its because all features start at -100 points, and it didn't make the cut. – asawyer Jun 03 '11 at 15:47
  • 2
    If you have methods that need calling during object initialisation then you should be calling them from a constructor and not leaving it to the dev who's using your class. – Lazarus Jun 03 '11 at 15:47
  • This a subjective question without a definite answer about somthing that doesen't exist. – Jodrell Jun 03 '11 at 15:58
  • @Lazarus - I'm not talking about methods that NEED to be called. I'm talking about methods that CAN be called. – Ronnie Overby Jun 03 '11 at 16:07
  • @Jodrell - There are questions like this all over stack overflow with definite answers why the c# team didn't do something with the language. – Ronnie Overby Jun 03 '11 at 16:08
  • You could at least have given a sample of how it would look like. And why, what would be the purpose/benefit? Good questions are still welcome. – H H Jun 03 '11 at 16:17
  • re Edit 2: I see now your motivation behind wanting this. Interesting...perhaps the C# team didn't think about usages like this. Alternatively (e.g. hackily) you could use a short variable name then reassign to the long variable when you're done... – NickAldwin Jun 03 '11 at 16:24
  • 1
    re Edit2: What if `AddChildren()` needs or changes the Name property? All kind of error scenarios become possible, for very little gain. – H H Jun 03 '11 at 16:48
  • @ Henk Holterman - The same thing could happen with property setters. There is very little gain whether you call methods or not. You gain saved time by not typing the variable name. – Ronnie Overby Jun 03 '11 at 17:10
  • I'm going to have to side with Ronnie on this. Despite the likely possibility of attracting speculative answers, there very well could be an objective reason especially if the hypothetical reason were technical in nature as has been the case with many feature omissions. It is similar to the many "Why can't `var` be used in class variable declarations?" variations which have no problems remaining open on SO. – Brian Gideon Jun 03 '11 at 18:12
  • 2
    It is an interesting idea. Ofcourse, to save typing you could do `var x = mySuperLong...` then `x.AddChildren(...` – Jodrell Jun 06 '11 at 08:24

5 Answers5

9

The answer is in the name -- object initializer syntax is syntactic sugar to visually group the object's initial state. Methods change the object state, so once it's changed, it's no longer the initial state.

For example: say you buy a car. It is a red coupe with 55,000 miles on it. Then, you decide to drive it. It ends up with 55,500 miles on it. It has changed from its initial state:

var c = new Car() {Color = "Red",
                   Style = Styles.Coupe,
                   Mileage = 55000};
// c.Mileage is 55,000
c.Drive();
// c.Mileage is 55,500

In this somewhat contrived example, the method has a side effect and thus changes the object from its initial 55,000mi state to a 55,500mi state. This is not the same thing as buying a car with 55,500 miles on it.

NickAldwin
  • 11,584
  • 12
  • 52
  • 67
  • 2
    Property setters are capable of altering state also. – Ronnie Overby Jun 03 '11 at 16:16
  • @Ronnie that's technically true--as Yuck's answer shows--but the idea behind properties is that they aren't methods; they don't hide what they are doing and possibly cause unseen changes – NickAldwin Jun 03 '11 at 16:19
  • Properties are designed to "read, write, or compute the value of a private field" [ http://msdn.microsoft.com/en-us/library/x9fsa0sw.aspx ] so while they may have side effects, properly designed properties should limit those side effects to only those that are necessary to set that value (and thus, it still jives with the idea of initial value). – NickAldwin Jun 03 '11 at 16:21
  • 1
    As an aside, I want to point out that, according to that description of properties, their intention is being raped every day by good developers coding any Silverlight or WPF MVVM view model. :) – Ronnie Overby Jun 03 '11 at 16:29
6

If you really want to do this, you could cheat I suppose...

class C {
    int BadProperty {
        set {
            SomeMethod(value);
        }
    }

    void SomeMethod(int value) {
        // here is where you do really, really bad things
    }
}

Then call it like this!

var fail = new C { BadProperty = 1 };
Yuck
  • 49,664
  • 13
  • 105
  • 135
3

what if the method fails ? The basic idea is, it's just a syntactic sugar. Eric Lippert is many time asked about "Why does C# not support feature X?". His answer is always

"because no one designed, specified, implemented, tested, documented and shipped that feature." - Eric Lippert.

this. __curious_geek
  • 42,787
  • 22
  • 113
  • 137
2

This is all about orders, the Class have to be initialized with all the fields and all declared methods, before it can be guaranteed to run a method safely.

Bolu
  • 8,696
  • 4
  • 38
  • 70
0

You can call methods with named parameters, if that is what you are asking about:

someMethod(param1: "Hello World", param2: "Some Other Value");
Tejs
  • 40,736
  • 10
  • 68
  • 86