In all C# applications, you typically build classes that contain properties and methods. Properties store data and methods perform work. Quite often you may encounter a situation where you need a property that contains information you can access from your application. However, you never want to perform method work directly inside the property. Instead, your properties and methods should perform their separate purposes and never the twain shall meet. You do this by letting your properties call the methods in your class.
Today’s code tip demonstrates how to do this.
Let’s begin with this scenario. Let’s suppose we have a data table in Microsoft SQL Server that contains a directory of church staff.
Now we’ll create a class library project and add a new class called Staff. The Staff class contains properties that match those fields in our data table.
Notice that I’ve also added a property of type DataTable called StaffTable. But notice like in the other properties there are no data operations taking place. All I’ve done is called a GetStaffTable() method by returning it to the StaffTable. Below is the method that I’m calling, which I’ve specified as private since I don’t want it to be accessible by any other part of the application save for a property inside the Staff class:
This code demonstrates a method that returns a DataTable object filled by a SQL data adapter. It also demonstrates the best practice of ensuring that your property data type matches your method data type. In C#, all properties and methods are what’s known as “strongly typed” to ensure that only like objects interact with each other.
Now that my method is complete and my property calls that method, I can now utilize it my web application. In this demonstration, I’ve created a new page called ChurchDirectory.aspx and added a GridView control to it. Now I instantiate a new instance of the Staff class and assign the StaffTable property as the data source of the GridView control:
When I launch the web page, I find my GridView populated with the information in the database table.
I hope you enjoyed this month’s code tip, and it’s now clear how to use properties and methods to interact with one another in C# classes.
God bless and happy coding!
Speak your mind...