Class Members C# Help

The data and functions within a class are known as the class’s members. Microsoft’s official terminology distinguishes between data members and function members. In addition to these members, classes can contain nested types (such as other classes). All members of a class can be declared as public (in which
case they are directly accessible from outside the class) or as private (in which case they are visible only to other code within the class), just as in Visual Basic, C++, and Java. C# also has variants on this theme, such as protected (which indicates a member is visible only to the class in question and to any derived classes).

Data Members

Data members are those members that contain the data for the class – fields, constants, and events. Data members can be either static (associated with the class as a whole) or instance (each instance of the class has its own copy of the data). As usual for object-oriented languages, a class member is always an instance member unless it is explicitly declared as static.

Fields are any variables associated with the class. You have already seen fields in use in the Phone Customer class in the previous example

Once you have instantiated a Phone Customer object, you can then access these fields using the Object. FieldName syntax, as shown in this example

Constants can be associated with classes in the same way as variables. You declare a constant using the constant keyword. Once again, if it is declared as public, it will be accessible from outside the class.

Events are class members that allow an object to notify a caller whenever something noteworthy happens, such as a field or property of the class changing, or some form of user interaction occurring. The-client can have code, known as an event handler, that reacts to the event.

Function Members

Function members’ are those members that provide some functionality for manipulating the data in the class. They include methods, properties, constructors, finalizers, operators, and indexers.

Methods are functions that-are associated with a particular class. They can be either instance methods, which work on a particular instance of a class, or static methods, which provide more generic functionality that doesn’t require you to instantiate a class (like the Console. WriteLine () method). Methods are discussed in the next section.

Properties are sets of functions that can be accessed from the client in a similar way to the public fields of . the class: C# provides a specific syntax for implementing read and write properties on your classes, so you don’t have to jury-rig methods whose names have the words Get or Set embedded in them. Because there’s a dedicated syntax for properties that is distinct from that for normal functions, the illusion of objects as actual things is strengthened for client code.

Constructors are special functions that are called automatically when an object is instantiated. They must have the same name as the class to which they belong and cannot have a return type. Constructors are useful for initializing the values of fields.

Finalizers are similar to constructors but are called when the CLR detects that an object is no longer needed. They have the same name as the class, preceded by-a tilde (-). C++ programmers should note that finalizers are used much less frequently in C# than their nearest C++ equivalent, destructors , because the CLR handles garbage collection automatically. Also, it is impossible to predict precisely when a finalizer will be called.

Operators, at their simplest, are actions like + or -. When you add two integers, you are, strictly speaking, using the + operator for integers. However, C# also allows you to specify how existing operators will work with your own classes (operator overloading).

Indexers allow your objects to be indexed in the same way as an array or collection.

Methods

In Visual Basic,C, and C++, you could define global functions that were not associated with a particular class. This is not the case in C#. As noted earlier, in.C# every function must be associated with a class or struct.

Note that official C# terminology does in fact make a distinction between functions and methods. In C# terminology, the term “function member” includes not only methods, but also other non data members of a class or struct. This includes indexers, operators, constructors, destructors, and also – perhaps somewhat surprisingly – properties. These are contrasted with data members: fields, constants, and events

Declaring Methods

The syntax for defining a method in C# is just what you’d expect from a C-style language and is virtually identical to the syntax in C++ and Java. main s tactical difference from C++ is that, in C#, each method is se paratel declared as public or private~ 1s not possible i e. blacks to group several method definitions. Also, all C# methods are declared an defined in the class definition. There is no facility- to separate the method implementation as there is in C++.

In C#, the definition of a method consists of any method modifiers {such as the method’s accessibility), the type of the return value, followed by the name of the method, followed by a list of input arguments enlosed in parentheses, followed by the body of the method enclosed in curly braces:

[modifiers] return_type MethodName([parameters])
(
II Method body

Each parameter consists’of the name of the type of the parameter, and the name by which it can be referenced in the body of the method. Also, if the method returns a value, a return statement must be used with the return value to indicate each exit point. For example:

This code uses one of the .NET base classes, System. Drawing. Rectangle, which represents a rectangle If the method doesn’t return anything, you specify a return type of void because you can’t omit the return type altogether, and if it takes no arguments, you still need to include an empty set of parentheses after the method name (as with the Main () method). In this case, including a return statement is optional- the method returns automatically when the closing curly brace is reached. You should note that a method can contain as many return statements as required:

The syntax for invoking a method is exactly the same in C# a’s it is in C++ and Java. And, the only difference between C# and Visual Basic is that round brackets must always be used when invoking the
method in C# – this is actually simpler than the.Visual Basic 6 set of rules whereby brackets were sometimes necessary and at other times not allowed,

The following example, MathTest, illustrates the syntax for definition and instantiation of classes, and definition and invocation of methods. Besides the class that contains the Main () method, it defines a class named MathTest, which contains a couple of methods and a field.

Img

Running the MathTest example produces these results,

csc MathTest .cs

Img

As you can see from the code, the MathTest class contains a field that contains a number, as well as a method to find the square of this number. It also contains two static methods, one to return the value of pi and one to find the square of the number passed in as a parameter.

Some features of this class are not really good examples of C# program design. For example, Getpi ( ) would usually be implemented as a const field, but following good design here would mean using some concepts that we have not yet introduced.

Most of the syntax in the preceding example should be familiar to C++ and Java develpors. If your background is in Visual Basic, just think of the MathTest class as being like a Visual Basic class module that implements fields and methods. There are a couple of points to watch out for though, whatever your language.

Passing Parameters to Methods

In general, parameters can be passed into methods by reference or by’ value. When a variable is passed by-reference, the called method gets the actual variable – so any changes made to the variable inside the method persist when the method exits. But, when a variable is passed by value, the called method gets an ilientical ~P}’ of the variable – which means any changes made.are lost when the method exits. For complex data types, passing by reference is more efficient because of the large amount of data that must be copied when passing by value. In C#, all parameters are a v lue unless ausetificall savorwise This.is the same behavior as in C++ ut e opposite of Visual Basic. However, you need to be careful in understanding the implications of this for reference types. Because reference type variables hold only a reference to an object, it is this reference that will be copied, not the object itself. Hence, changes made to the underlying object will persist. ,value type variables, in contrast, hold the actual data, so a copy of the data itself will be passed into the method. An int, for instance, is passed by value to a method, and any changes that the method makes to the value of that int do not change the value of the original int object. Conversely, if an array or any other reference type, such as a class, is passed into a method, and the method uses the reference to change a value in that array, the new value is reflefted in the original alfay object

Here is an example, Parameter Test. cs, that demonstrates this;

Img

Notice how the value of f remains unchanged, but the-value changed in Int s is also changed in the original array.

The behavior of strings is different again: This is because strings are immutable (if you alter a string’s value, you create an entirely new string), so strings don’t display the typical reference-type behavior. Any changes made to a string within a method call won’t affect the original string.

ref Parameters

As mentioned, passing variables by value is the default, but you can force value parameters to be passed by reference. To do so, use the ref keyword. If a parameter is passed to a method, and if the input argument for that method is prefixed with the ref keyword, any changes that the method makes to the variable will affect the value of the original object:

Img

You will also need to add the ref keyword when you invoke the method:

SomeFunction(ints, ref i);

Adding the ref keyword in C# serves the same purpose assuming the & syntax in C++ to specify passing by reference. However, C# makes the behavior more explicit (thus hopefully preventing bugs) by requiring the use of the ref keyword when invoking the method.

Finally, it is also important to understand that C# continues to apply initialization requirements to parameters passed to methods. Any variable must be initialized before it is passed into a method, whether it is passed in by value or by reference.

out Parameters

In C-style languages, it is common for functions to be able to output more than one value from a single routine. This is accomplished using output parameters, by assigning the output values to variables
that have been passed to the method by reference. Often, the starting values of the variables that are passed by reference are unimportant. Those values will be overwritten by the function, which may never even look at any previous value.

It would be convenient if you could use the same convention in C#. However, C# requires that variables be initialized with a starting value before they are referenced. Although you could initialize your input variables with meaningless values before passing them into a function that will fill them with real, meaningful ones, this practice seems at best needless and at worst confusing. However, there is a way to short-circuit the C# compiler’s insistence on initial values for input arguments.

You do this with the out keyword. When a method’s input argument is prefixed with out, that method can be passed a variable that has not been initialized. The variable is passed by reference, so any changes that the method makes to the variable will persist when control returns from the called method. Again, you also need to use the out keyword when you call the method, as well as when you define it:

Img

The out keyword is an example of something new in C# that has no analogy in either Visual Basic or C++ and that has been introduced to make C# more secure against bugs. If an out parameter isn’t assigned a value within the body of the function, the method won’t compile.

Method Overloading

C# supports method overloading – several versions of the method that have different signahires is, the same name, but a differentnumber of parameters and or different parameter data types).
However, C# does not support default parameters in the way that, say, C++ or Visual Basic does. In order to overload methods, you simply declare the methods with the same name but different numbers or types of parameters:

Img

Because C# does not support optional parameters, you will need to use method overloading to achieve the same effect:

Img

As in any language, method overloading carries with it the potential for subtle runtime bugs if the wrong overload is called. Chapter 4 discusses how to code defensively against these problems. For now, you should know that C# does place some minimum differences on the parameters of overloaded methods:

It is not sufficient for two methods to differ only in their return type,.

It is not sufficient for two methods to differ only by virtue of a parameter having been declared as ref or out .

Properties

properties are unusual in that they represent an idea that C# has taken from Visual Basic, not from C++ and Java .The idea of a property is that is a method or pair of methods that are dressed to look like a field as as any client code is concerned A good example of this is the Height property of a Windows Form. Suppose that you have the follow g code:

//mainForm is of type System,Windows,Forms” mainForm.Height = 400;

On-executing this code, the height of the window will be set to 400, and you will see the window resize on the screen. Syntactically, this code looks like you’re setting a field, but in fact you are calling a property accessor that contains code to resize the form,

To define a property in C#, you use the following syntax:.

Img

The get accessor takes no parameters and must return the same type as the declared property. You should not specify any explicit parameters for the set accessor either, but the compiler assumes it takes one parameter, which is of the same type again, and which is referred to as value. As an example, the following code contains a property called ForeName, which sets a field called foreName and applies a length limit:

Img

Note the naming convention used here. You take advantage of C#’s case sensitivity by using the same name, Pascal-cased for the public property, and camel-eased for the equivalent private field if there is one. Some developers prefer to use field names that are prefixed by an underscore: _foreName; this provides an extremely convenient way of identifying fields V”JSual Basic 6 programmers should remember that C# does not distinguish between VIsual Basic6 Set and Visual Basic6 Let: In C#, the write accessor is always identified with the keyword set.

Read-Only and Write-Only Properties

It is-possible to create a read-only property by simply omitting the set accessor from the property definition. Thus, to make ForeName read-only in the previous example:

Img

It is similarly possible to create a write-only property by omitting the get accessor. However, this is regarded as poor programming practice because it could be confusing to authors of client code. In general, it is recommended that if you are tempted to do this, you should use a method instead.

Access Modifiers for Properties

C# does allow the set and get accessors to have differing access modifiers. nus would allow a property to have a public get and a private or protected set. This can help control how or when a property can be set. In the following code example, notice that the set has a private access modifier and the get does not have any. In this case, the get takes on the access level of the property. One of the accessors must follow the access level of the property. A compile error will be generated if the get accessor has the protected access level associated with it because that would accessors a different access level from the property.

Img

Auto-Implemented Properties

If there isn’t going to be any logic in the properties set and get, then auto-implemented properties can be used. Auto-implemented properties implement the backing member variable automatically. The code for the previous example would look like this:

public string ForeName {get; set;}

The decIaration private string foreName; is not needed. The compiler will create this automatically.

public string ForeName {get;}

However, the access level of each accessor can be different. So the following is acceptable:

public string ForeName {get;_private set;}

Constructors

The syntax for declaring basic constructors in C# is the same as in Java and C++. You declare a method that has the same name as the containing class and that does not have any return type:

Img

As in C++ and Java, it’s not necessary to provide a constructor for your class. We haven’t supplied one for any of the examples so far in this book. In general, if you don’t supply any constructor, the compiler will just make up a default one for you behind the scenes. It will be a very basic constructor that just initializes all the member fields by zeroing them out (null reference for reference types, zero for numeric data types, and false for boo Is). Often, that will be adequate; if not, you’ll need to write your own constructor.

For C++ programmers: Because primitive fields in 0# are by default initialiZed by being zeroed out. whereas primitive fields in C++ are by default uninitialized, you may find that you don’t need to write constructors in C, as often as you would in C++.

Constructors follow the same rules for overloading as other methods (that is, you can provide as many overloads to the constructor as you want, provided they are clearly different in signature):

img

Note, however, that if you supply any constructors that take parameters, the compiler will not automatically supply a default one. This is done only if you have not defined any constructors at all. In the following example, because a one-parameter constructor is defined, the compiler assumes that this is the only constructor you want to be available, so it will not implicitly supply any others:

Img

This code also illustrates typical use of the this keyword to distinguish member field from parameters of the same name. If you now try instantiating a MyNumberobject using a no-parameter constructor, you will get a compilation error:

Img

We should mention that it is possible to define constructors as private or protected, so that they are invisible to code in unrelated classes too:

Img

This example hasn’t actually defined any public or even any protected constructors for MyNumber.This would actually make it impossible for MyNumber to be instantiated by outside code using the new operator (though you might write a public static property or method in MyNumberthat can instantiate the class). This is useful in two situations:

If your class serves only as a container for some static members or properties and therefore should never be instantiated.

If you want the class to only ever be instantiated by calling some static member function (this is the so-called class factory approach to object instantiation)

Static Constructors

One novel feature of C# is that it is also possible to write a static no-parameter constructor for a class. Such a constructor will be executed only once, as opposed to the constructors written so far, which are instance constructors that are executed whenever an object of that class is created, There is no equivalent to the static constructor in C++ or Visual Basic 6.

Img

One reason for writing a static constructor is if your class has some static fields or properties that need to be initialized from an external source before the class is first used.

The .NET runtime makes no guarantees about when a static constructor will be executed, so you should’ not place any code in it that relies on it being executed at a particular time (for example, when an assembly is loaded). Nor is it possible to predict in what order static constructors of different classes will execute .’However, what is guaranteed is that the static constructor will run at most once, and that it will be invoked before your code makes any reference to the class. In C#, the static constructor usually seems to be executed immediately before the first call to any member of the class.

Notice that the static constructor does not have any access modifiers. It’s never called by any other C# code, but always by the .NET runtime when the class is loaded, so any access modifier like public or private would be meaningless. For this same reason, the static constructor can never take any parameters, and there can be only one static constructor for a class. It should also be obvious that a static constructor can access only static members, not instance members, of the class.

Note that it is possible to have a static constructor and a zero-parameter instance constructor defined in the same class. Although the parameter lists are identical, there is no conflict. That’s because the static constructor is executed when the class is loaded, but the instance constructor is executed whenever an instance is created – so there won’t be any confusion about which constructor gets executed when.

Note that if you have more than one class that has a static constructor, the static constructor that will be executed first is undefined. This means that you should not put any code in a static constructor that depends on other static constructors having been or not having been executed. However, if any static fields have been given default values, these will be allocated before the static constructor is called.

The next example illustrates the use of a static constructor and is based on the idea of a program that has user preferences (which are presumably stored in some configuration file). To keep things simple, we’ll assume just one user preference – a quantity called BackColor, which might represent the background color to be used in an application. And because we don’t want to get into the details of writing code to read data from an external source here, we’ll make the assumption that the preference is to have a background color of red on weekdays and green on weekends. All the program will do is display the preference in a console window – but this is enough to see a static constructor at work.

Img

This code shows how the color preference is stored in a static variable, which is initialized in the static constructor. This field is declared as read-only, which means that its value can only be set in a . constructor. You learn about read-only fields in more detail later in this chapter. The code uses a few helpful structs that Microsoft has supplied as part of the Framework class library, System. DateTime and System. Drawing. Color. DateTime implements both a static property, NOW, which returns the current time, and an instance property, DayofWeek, which works out what day of the week a date-time represents. color (which is discussed in Chapter 33, “Graphics with GDI+”) is used to store colors. It implements various static properties, such as Red and Green as used in this example, which return commonly used colors. In order to use Color, you need to reference the System. Drawing. dll assembly when compiling, and you must add a using statement for the System. Drawing namespace:

img

Of course ifthe code isexecuted during the weekend, your color preference would be Green.

Calling Constructors from Other Constructors

You may sometimes find yourself in the situation where you have several constructors in a class,perhaps to accommodate some optional parameters, for which the constructors have some code in common. For example, consider this:

IMg

Both constructors initialize the same fields.It would clearly be neater to place all the code in one place, and C# has a specialsyntax, known as a constructor initializer to allow this:

Img

In this context, the this keyword simply causes the constructor with the nearest matching parameters to be called. Note that any constructor initializer is executed before the body of the constructor. Say that the following code is run:

Car rnyCar = new Car(‘Proton Persona’);

In this example, the two-parameter constructor executes before any code in the body of the one parameter constructor (though in this particular case, because there is no code in the body of the one-parameter constructor, it makes no difference).

A C# constructor initializer may contain either one call to another constructor in the same class (using the syntax just presented) or one call to a constructor in the immediate base class (using the same syntax, but using the keyword base instead of this). It is not possible to put more than one call in the initializer.

The syntax for constructor,initializers in C# is similar to that for constructor initialization lists in C++, but C++ developers should beware: Behind the similarity in syntax, C# initializers follow very different rules for what can be placed in them. Whereas you can use a C++ initialization list to indicate initial! values of any member variables or to call a base constructor, the only thing you can put in a C# initializer is one call to one other constructor. This forces C# classes to follow a strict sequence for how they get constructed, whereas C++ allows some leniency.

readonly Fields

The concept of a constant as a variable that contains a value that cannot be changed is something that C# shares with most programming languages. However, constants don’t necessarily meet all requirements.
On occasion, you may have some variable whose value shouldn’t be changed, but where the value is not known until runtime. C# provides another type of variable that is useful in this scenario: the readonly field. The readonly keyword gives a bit more flexibility than const, allowing for situations in which you might want a fielcMt>be constant but also need to carry out some calculations to determine its initial value. The rule is that you can assign values to a readonly field insidea constructor, but not anywhere . else. It’s also possible for a readonly field to be an instance rather than a static field, having a different value for each instance of a class. This means that, unlike a const field, if you want a readonly field to be static, you have to declare it as such.

Suppose that you have an MDI program that edits documents, and, for licensing reasons, you want to restrict the number of documents that can be opened simultaneously. Now assume that you are selling dlfferent versions of the software, and it’s possible that customers can upgrade their licenses to open more documents simultaneously. Clearly this means you can’t hard-code the maximum number in the source code. You’d probably need a field to represent this maximum number. This field will have to be read in – perhaps from a registry key or some other file storage – each time the program is launched. Soyour code might look something like this:

Img

In this case, the field is static, because the maximum number of documents needs to be stored only once per running instance of the program. This is why it is initialized in the static constructor. If you had an instance readonly field, you would initialize it in the instance constructor(s). For example, presumably each document you edit has a creation date, which you wouldn’t want to allow the user to change (because that would be rewriting the past!). Note that the field is also public – you don’t normally need to m1.ke readonly fields private, because by definition they cannot be modified externally (the same principle also applies to constants).

As noted earlier, date is represented by the class System. DateTime. The following code uses a System . DateTime constructor that takes three parameters (the year, month, and day of the month – you can find details of this and other DateTime constructors in the MSDN documentation):

Img

CreationDate and MaxDocuments in the previous code snippet are treated like any other field, except that because they are read-only, they cannot be assigned outside rile constructors:

Img

It’s also worth noting that you don’t have to assign a value to a readonly field in a constructor. If you don’t do so, it will be left with the default value for its particular data type or whatever value you initialized it to at its declaration. That applies to both static and instance readonly fields.