DEV Community


Posted on

Visual Studio: How to Quickly Instantiate classes

Visual Studio: How to Quickly Instantiate classes


Early on in my career I found myself questioning the Object Oriented approach at every turn. Implementing and using classes can be a little intimidating when you are first starting to use them . It can also feel like a waste of time, because not only do you need to spend time planning them out, and utilizing precious extra keystrokes to create them. Each time you want to use a class, it requires you to remember each of the member variables and exactly how you spelled them. If we go a little deeper into an actual use case it can be troublesome having to write test cases for each class that we built. To build test cases we need to populate sample data into each of our classes. How can we do that quickly and easily?

Here is a quick tip that will help you quickly and efficiently instantiate classes while using Visual Studio.

Let's say that we have a Customer class that has a whole range of members defined and now it comes time to instantiate a customer object in our program.

One way to do this is to create a new Customer object.

Customer customer = new Customer();

and after instantiating the customer object we can fill in each of the members with test data like so.

customer.Address = "something";

customer.TelephoneNumber = "something";

customer.NextMember = "something";

This is not a real world example, most of the business objects we use in the workplace have 20+ members. On top of that we often create classes in batches.

When it comes time to write test cases it can be difficult to remember what all the naming conventions were if we attempt to populate them as I did above.

A simple trick to make this process a little more palatable is to instantiate your class as i do below.

Instead of creating a new empty class and then assigning the members after. Use curly braces after the "new Customer" declaration.

Customer customer = new Customer



Then place your cursor somewhere in the body of the curly braces and hit "ctl + spacebar". This will bring up auto complete which will display a list of all of the member variables that are available to the class.

Then hit "Tab" which will auto select and populate the first member.

Then "spacebar" , "=" and give it a value.

Hit comma "," and then repeat the process until you have finished.

Visual Studio is smart enough to only give you values that you have not set. You can use this method to work your way through every member until you have them all filled out.



Top comments (0)