Methods


Methods are fundamental to designing classes in C#. They represent actions associated with a class. Methods typically perform actions that manipulate the object's state. However, this isn't always the case. For instance, you can declare a method as a static method. A static method might provide specific functionality, but it cannot work on an object's state. As with our other discussions around static things, a static method belongs to the class and not each specific instance.

All methods have a name, a parameter list, and a return type. As we will see, it is also possible to define multiple methods with the same name as long as they contain different signatures. Methods are discussed in more detail in the next chapter.

Method Overloading

The method signature includes the method's name, and the number and type of parameters. For example, if two methods with identical names differ only by their number and types of parameters, the .NET Framework considers the methods different. The practice of creating methods with same names and different signatures is called method overloading. If two methods exist in the same class or struct, with the same signature, the compiler will generate an error on compilation.

Note that our description of a method's signature does not include a return type. This is because methods in C# cannot be overloaded based solely on the return type. This rule is not enforced by the .NET platform, but rather by the C# language. The CLR supports the ability for two or more methods to only differ by return type, however the C# language (and many other .NET languages including VB.NET) do not. A compiler error will be generated if two methods in the same class differ only by return type. Each language enforces the restriction, not the .NET runtime. In practice, the issue is seldom a limiting factor in class design.




C# Class Design Handbook(c) Coding Effective Classes
C# Class Design Handbook: Coding Effective Classes
ISBN: 1590592573
EAN: 2147483647
Year: N/A
Pages: 90

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net