Giffyguy
Giffyguy

Reputation: 21302

What's the best way to initialize a public property in C#?

I need to give my properties initial values, and I'd like to know if there is a simpler way than using a constructor.

Upvotes: 0

Views: 348

Answers (5)

Brian Rasmussen
Brian Rasmussen

Reputation: 116481

I like to think about this a bit differently. If the value is something that is mandatory for the creation of an instance, it needs to be a parameter for the constructor.

However, if the value is optional then setting it via a property is fine.

Upvotes: 2

ace
ace

Reputation: 2181

If you just want to initialize the property values, then constructors are simply enough I don't see why you think they are not simple.

However you can do this if you want, you can initialize the variable like this :

int _myProperty = 5;
public int MyProperty
{
  get{ return _myProperty ;}

 set { _myProperty=value; }
}

Upvotes: 2

Mufaka
Mufaka

Reputation: 3444

If you are taking advantage of automatic properties, the constructor is the easiest way. If you are not, then your member variable can define the default value.

private string _someString = "Hello.";

But, you'll have to define the getter and setter yourself.

public string SomeString
{
    get { return _someString; }
    set { _someString = value; }
}

Which wouldn't be simpler than just defining the default in the constructor.

Upvotes: 2

Unmesh Kondolikar
Unmesh Kondolikar

Reputation: 9312

Are you using automatically implemented properties? The value type properties will be initialized to their default values. Reference types will be initialized to null.

If you want them to initialize them to some other I think the best option is to set them in the constructor.

If you are not using automatically implemented properties you can initialize them where they are declared.

It will also be useful to keep in mind the order in which the objects fields and constructors are initialized.

Upvotes: 2

Singleton
Singleton

Reputation: 3679

Well Constructors are best for doing this. How ever u can call a methods too.

Check following link too Initializing C# auto-properties

Upvotes: 1

Related Questions