-3

For any given class, obviously I would have something like:

public class Stuff {
    int field1;
    int field2;
    // [etc.]
    public Stuff (int field1In, int field2In) {
        field1 = field1In;
        field2 = field2In;
    }
}

However, for many fields, indirectly assigning properties from parameters like this seems ugly and indirect. Is there any more direct way? For instance, where instead of specifying a parameter name, you could just specify the fields name, and it would directly assign it?

  • maybe reflection what you need – Grundy Nov 14 '13 at 09:09
  • There doesn't seem to be any elegant/simple solution here. You could try aspect-oriented programming, like PostSharp to tailor the code to your needs. Alternatively, some development support tools, like Resharper help a lot with generating such code (in fact it takes a few keystrokes). – decPL Nov 14 '13 at 09:09
  • Suggest it to Eric Lippert and convince him that it's an important feature. – Tim Schmelter Nov 14 '13 at 09:11
  • 1
    @TimSchmelter Eric is no more in MSFT, suggest Andres..:) – Sriram Sakthivel Nov 14 '13 at 09:12
  • 1
    When you say "many properties", how many do you mean? If it's enough that writing some assignment statements (even without something like ReSharper) seems onerous, you might want to reconsider your class design. Obviously your post is just an example, but if you're passing in dozens of `ints` or other primitive types, for example, you should consider whether it isn't better to group those values into classes which make sense for your problem domain. – anton.burger Nov 14 '13 at 09:14
  • "seems ugly and indirect" ? I don't think so. When language says you've to use `field = expression;` you've to follow that. – Sriram Sakthivel Nov 14 '13 at 09:14
  • 1
    'int prop1;' is not a property. It would be called field or member but not property. See [MSDN](http://msdn.microsoft.com/en-us/library/x9fsa0sw(v=vs.110).aspx) for more info. –  Nov 14 '13 at 09:15
  • This is not a property. This is a method which expects two ints. If you want a more direct appearance use public vars but that would be bad design. What a pitty... – user1567896 Nov 14 '13 at 09:15
  • I apologize for my misuse of the word "property". I always get field and property mixed up for whatever reason. I've updated the question to account for this. – Trey Stone Nov 15 '13 at 20:42

1 Answers1

0

I'm guessing the reason why you want to initialize fields in the constructor is for immutability reasons, but since you haven't made the fields readonly (and you've called your fields prop), you can obviously also use the property initializer syntactic sugar, if you change your fields to properties, reducing your LOC as follows:

public class Stuff {
    public int Prop1 {get; set;}
    public int Prop2 {get; set;}
}

Caller would just use the default constructor:

var myStuff = new Stuff() {
  Prop1 = 54,
  Prop2 = 88
}

Edit

I guess to sum up the below banter:

  • If 'prop1' et al are to be retained as fields, then there is no shorthand.
  • If 'prop1' et al need to be kept private (albeit initialized externally) then there is also no shorthand.
  • If the fields can be converted to publically setable properties, then you can use automatic properties, as per above.

However, and I’m speculating here, if your question is as a requirement of using ctor initializers for the purpose of promoting the immutability of your fields, it would be nice to allow a hybrid syntactic sugar allowing for a combination of immutability similar to autoproperties which will reduce the LOC.

Several folk are already calling for readonly automatic properties to be implemented in C#, although it is speculative as to whether this extend to initializer syntax as part of the constructor.

This might allow the typical verbose pattern of:

class SomeClass
{
    private readonly SomeDependency _dep1;
    private readonly AnotherDependency _dep2;
    . . .

    public SomeClass(SomeDependency dep1, AnotherDependency dep2, …)
    {
      _dep1 = dep1;
      _dep2 = dep2;
      …
    }

To be replaced with simpler, yet equivalent code. I have absolutely no idea what the syntax would look like ... but it would mean a property (or field) is "private readonly" except for the one exception of CTOR initializer syntax ...

"ReadOnly" SomeDependency Dep1 { private get; private set; } 
"ReadOnly" SomeDependency Dep1 { private get; private set; }
. . . No need for ctor since can just use the default constructor

And which could then be used at construction time:

var x = new SomeClass
{
  Dep1 = ...,
  Dep2 = ...
};  // OK, this time only, because it is at construction time.

But not mutated

x.Dep1 = ...; // Compile time err ...

And obviously the requirement would be that ALL such properties must be initialized simultaneously (or just be baked with the type default for the object's lifespan )...

Community
  • 1
  • 1
StuartLC
  • 104,537
  • 17
  • 209
  • 285
  • 2
    Does that work for private properties? **EDIT**: No, it doesn't work – musefan Nov 14 '13 at 09:15
  • IMO don't answer to these kind of questions. Op will come with another question saying "Oh boring I need to set value everywhere I create an instance"? – Sriram Sakthivel Nov 14 '13 at 09:16
  • @musefan nope, it doesn't work for private `properties`, obviously :) But OP has called his fields 'prop1` etc, hinting that he is also open to the use of Properties. – StuartLC Nov 14 '13 at 09:20
  • Then what is the point in this non-answer, which doesn't attempt to answer the q and changes the q in order to shoehorn a solution to something else? – Grant Thomas Nov 14 '13 at 09:23
  • @GrantThomas OP has called his fields `prop1` et al, which may indicate he / she is open to other design suggestions. – StuartLC Nov 14 '13 at 09:24
  • 1
    I have removed my downvote as you have made then public and that will technically work (although the semi-colons in your construction are problematic). But I still don't agree with changing the design just to allow this type of construction – musefan Nov 14 '13 at 09:26
  • But you don't even make that argument, this just slyly changes the definition to fit the potential needs without explaining such implications. – Grant Thomas Nov 14 '13 at 09:26