O'Reilly logo

Microsoft®C# Programming for the absolute beginner by Andy Harris

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Creating a Constructor

Imagine that you want to write a program using several critters. Each critter could have a different name and different characteristics (perhaps different starting values for hunger and happiness). Using the Critter class from Chapter 4, you could do it, but you’d have to create each critter in several steps. First, you’d have to create the critter, and then you’d need another statement of code to modify each characteristic. It would look something like this:

Critter myCritter = new Critter();
myCritter.name = "alpha";
myCritter.age = 10; 

Although this is not difficult, a more convenient way to create a critter would enable you to initialize all its values at the same time. You could set up a critter with a line like this: ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required