Methods
Methods are the workhorses of your classes. When you call a method, it executes some code. It may, but doesn't have to, return some value directly. It may also take some parameters, but again, it doesn't have to.
Listing 2.9. Basic method with no return value
C#
VB.NET
public void MyMethod()
{
// some code
}
If you'd like the method to return some kind of value, you'll need to declare its type in the method declaration, and then at some point (or points) in the method, you'll need to return the value with the return keyword, as shown in Listing 2.10.
Public Sub MyMethod()
' some code
End Sub
Listing 2.10. A method that returns a string
C#
VB.NET
public string MyMethod()
{
return "some string";
}
Notice the difference in syntax compared to Listing 2.8, where the method does not return a value, especially if you're using VB.NET. When you need to return a value, you use the Function syntax instead of the Sub syntax. In C#, when you don't intend to return any value, you use the pseudo-type void.You probably have used methods that return a value, even if you haven't used that value. For example, if you've called the ExecuteNonQuery() method of a SqlCommand object, that method returns an integer indicating the number of rows in the database that were affected by your command (i.e., myInteger = SomeSqlCommand.ExecuteNonQuery()). If you don't capture that value, it's simply not used.Methods can give you something back, but you also can put something into a method as well by feeding it parameters. A method can have any number of parameters of any types. Listing 2.11 shows a method that takes a string and an int.
Public Function MyMethod() As String
Return "some string"
End Function
Listing 2.11. Method with parameters
C#
VB.NET
public void MyMethod(string myName, int myAge)
{
Trace.Warn(myName);
Trace.Warn(myAge.ToString());
}
You can now see that there are really two primary ways to get data in and out of your instantiated objects. You can use parameters and return values in your methods, or you can assign and read values from properties.Alternatively, you can do both. We'll look closer at both approaches in Chapter 3, "Class Design."Public methods can be called from any instance of the class. So what good are private methods? Suppose you have some common piece of code that other methods in the class need to call, but you don't want that common code to be called directly from an instance of the class. Marking the method private accomplishes this, and it's a handy way to avoid code duplication in your class.
Public Sub MyMethod(myName As String, myAge As Integer)
Trace.Warn(myName)
Trace.Warn(myAge.ToString())
End Sub