Dynamic properties when calling base?

Started by
3 comments, last by Headkaze 11 years, 5 months ago
I really like how I can use dynamic properties when creating a new object.

Eg. MyObject myObject = new MyObject() { Property1 = something, Property2 = somethingElse };

It saves me having to create a bunch of overloaded constructors and it makes it easier to see what values I'm setting (kinda like Objective C).

Now I'd like to do this when calling base on a subclass constructor.

ie. void MySubObject(int something, int somethingElse)
: base() { Property1 = something, Property2 = somethingElse }

I'm getting an error so I assume the syntax is either incorrect or I can't do this.
Advertisement
You're close, but not quite. The following should work:

public class BaseClass
{
public BaseClass(int property1, int property2) { }
}

public class SubClass : BaseClass
{
public SubClass(int property1, int property2) : base(property1, property2) { }
}
I know I can pass in parameters like that but that wasn't my question. Nevermind though as it is so blatently obvious how to do what I want without needing a bunch of overloaded constructors.

ie.
void MySubObject(int something, int somethingElse)
: base()
{
Property1 = something;
Property2 = somethingElse;
}


The difference being you set the properties in the constructor's block and not into the base class block and you separate the properties being set by semicolon's instead of commas.
Just for the record, what you are using is called the object initialization syntax. Dynamic properties are something else entirely.
if you think programming is like sex, you probably haven't done much of either.-------------- - capn_midnight

Just for the record, what you are using is called the object initialization syntax. Dynamic properties are something else entirely.


Thanks for that; knowing what it's called is helpful. I really like the feature alot.

This topic is closed to new replies.

Advertisement