In addition to the state, the behavior of the objects is described in the class. We created the second Dog object without using a string for the name of the dog in the constructor.
Access Level "public"
Access Level "private"
Access Level "internal"
Assembly
Declaring Classes
In addition to the reserved word class and the class name, several modifiers can be used in the class declaration, e.g.
Class Visibility
If we want to be exhaustive, we should mention that the private visibility modifier can be used as an access modifier for a class, but this is related to the term "inner class", which we will discuss in "Nested". Classes". Private classes like other private members are only accessible within the class that defined them.
Body of the Class
Class Naming Convention
The Reserved Word "this"
We will do this later in other sections of this chapter, which are devoted to class elements (fields, methods, constructors) and are also associated with the this keyword.
Fields
Declaring Fields in a Class
As for the name of the normal variables, when we declare the name of the instance variables, we must follow the rules for naming identifiers in C# (see chapter "Primitive types and variables"). The scope of a class field starts from the line where it is declared and ends at the closing parenthesis of the class body.
Initialization during Declaration
The
Default Values of the Fields
As explained at the beginning of this section, const and readonly modifications are allowed in a single field declaration. Fields declared as read-only allow one-time initialization at declaration time or in class constructors.
Declaring of Class Method
In this section we will review how we do this and focus on some additional features from the method creation process.
Accessing Non-Static Data of the Class
Accessing Non-Static Fields from Non-Static Method
Apart from retrieving the value of a field, we can use the reserved word this for modifying the field.
Calling Non-Static Methods
Although it is clearly understood, the reserved word this is often used to access fields in the classroom because it helps make the code easier to read, understand, and maintain, by explicitly stating that we are accessing a field and not to a local variable. If the reserved word is not explicitly required, it can be skipped when we access the elements of the class.
Hiding Fields with Local Variables
Sometimes the name of a local variable may overlap with the name of a field. If this happens, the scope of the local variable is said to overlap the field variable (scope overlap).
Visibility of Fields and Methods
The access to the member of the class is done directly within the same class (the class refers to itself). The access to the member of the class is done via a reference to an object created in the body of another class (the class refers to another class).
Kid.cs class Kid
As we can see, we easily implement access to the field name and the Bark() method of the Dog class from the body of the same class. Regardless, if the namespace of the Kid class is the same as Dog, we can access the field name from its body and call the Bark() method via .
Dog.cs class Dog
Elements of the class that are declared with the access modifier private (or without any, because private is the default) cannot be accessed outside the class in which they are declared. The access and modification of the value from other classes (if required) will only be done via properties or methods.
How to Decide Which Access Level to Use?
Everything works because the access modifiers for the elements of the class are applied to the class and not to a level objects. If we try to do the same in the body of the class Kid, it will not be possible because the access to private fields from outside the class is prohibited.
Constructors
Since the myDog variable is defined in the body of the Dog class (where Main() - the program's startup method - is also located), its elements (fields and methods) can be accessed via the "dotted" notation, regardless of the fact that we declared the access level as privately.
What Is a Constructor?
If the creation of the new object is completed successfully, the constructor returns a reference to it, which is assigned to the myDog variable of the Dog: class.
Declaring a Constructor
In the example constructor of the Dog class, there is no need for additional data to create an object of this type and therefore there is no parameter list. It is clear that modifiers can be added in the declaration of the constructors –
Visibility of the Constructors
Similar to the methods, if we need additional data to create an object, the constructor gets it through a parameter list –
Initialization of the Fields in the Constructor
Then the constructor will have to ensure the creation of the object for the field name. At this time the fields are given the values set in the body of the constructor.
Declaring a Constructor with Parameters
Only after these two steps of initializing the class fields (initializing the default value and any value that the programmer sets during the field declaration) is the class constructor called. The explanation is as follows: the range in which the variables from the list of constructor parameters operate overlaps the range of operation of the fields.
Constructor with Variable Number of Arguments
The parameter for the variable number of arguments must be the last in the constructor parameter list. The first parameter in the statement is the name of the lecture course and the next parameter represents a variable number of arguments - the names of the students.
Constructor Overloading
Accordingly, since the first parameter is the name of the subject – “Biology”, and all remaining arguments – the names of the students present. On the other hand, it was mentioned at the beginning of the chapter that a constructor cannot be called the way the.
Default Constructor
The default constructor is usually public (except in some very specific situations where it is protected). If we declare at least one constructor in a given class, the compiler will not create a default constructor for us.
Properties
We try to call a constructor with no parameters in it, hoping that the compiler will have created a default parameterless constructor for us. Although the default constructor and the parameterless one are similar in signature, they are completely different.
Properties – Encapsulation of Fields
Point.cs class Point
The fields of the objects in our class (ie the coordinates of the point) are declared private and cannot be accessed with a "point" notation. If we create an object from the Point class, we can change and read the properties (coordinates) of the point only through the properties to access them:.
PointTest.cs using System;
Point.cs using System;
The demo is a good example of data encapsulation of an object, provided by the mechanism of the properties. Of course, the example only shows one of the advantages of class fields being wrapped (packaged) in properties.
Physical Presentation of the Properties in a Class
Through them we hide the internal representation of information by declaring properties and access methods to it, and if later a change in representation occurs, it will not affect other classes that use our class, because they only use its properties and they don't know. how information is presented "behind the scenes". Properties allow further control over the data in the class and can check whether certain values are correct according to some criteria.
Rectangle.cs using System;
Declaring Properties in C#
In the last line where the value 3 is set, the Age property setter method is called. This way the value is stored in the parameter value and assigned to the setter method of the Age property.
Automatic Properties in C#
To protect against invalid data, a class must validate input values for all properties and constructors passed to setter methods, as well as any methods that can modify a class field. This programming practice of protecting classes against invalid data and invalid internal state is widely used and is part of the concept of "defensive programming", which will be discussed in the chapter "High Quality Programming Code".
Types of Properties
These properties do not have explicitly defined underlying fields, and the compiler defines them during compilation. Use automatic properties for simple classes where you want to write less code, but remember that when you use automatic properties, your control over the assigned values is limited.
Static Classes and Static Members
The get and set methods appear to be empty, but in fact the compiler defines an underlying field and fills the body of the get and set accessors with code to read / write the automatically defined underlying field.
What the Static Elements Are Used For?
In practice the behavior of the method does not depend on the state of the object (the values in the object's field). Each single object will retain its own field to indicate the number of objects, and the objects will not be able to share information.
What Is a Static Member?
So why the need to create an object to reach that method, provided the method does not depend on any of the objects of that class. Let's say we want to keep the current number of objects created by a given class in our program.
Static Fields
This means that all objects created by the description of a class share the static fields of the class. All objects created by the description of a given class (that is, instances of a given class) share the static fields of the class.
Dog.cs public class Dog
If during the declaration of the static field we set an initialization value, it will be assigned to the particular static field. That way, any object can access and change the static field values, and at the same time, other objects can "see" the changed values.
Constants
If we don't give a value to a constant at its declaration, but later, we will get a compilation error. We will use the so-called Red-Green-Blue (RGB) color model, after which each color is represented by mixing the three primary colors – red, green and blue.
Color.cs class Color
The class compilation problem in our case has to do with reference types and the compiler's limitation of not allowing the new operator to be used concurrently with a constant declaration when that constant is declared with the const modifier, unless the reference type can be computed at compile time. When we want to declare reference type constants that cannot be computed at compile time, we must use a combination of read-only static modifiers instead of the const modifier.
Static Methods
Access between Static and Non-Static Members
We can access static fields and static methods of the class from non-static method. When we try to access non-static elements of the class (fields or methods) from static method, we will always get a compilation error.
Static Properties of the Class
Before moving on to the next section, let's take a look at the property vendor's printed value. Static properties can only be accessed through the dot notation used for the name of the class in which they are declared.
Static Classes
Static Constructors
If the program never needs to calculate the square root, preliminary calculations should not be performed at all. All this can be implemented in one static class with a static constructor, in which the square roots are recalculated.
Structures
Structure (struct) – Example
Point2D.cs struct Point2D
They are value types (not objects), which means they cannot be null and they are passed by value when taken as a method parameters.
Structures are Value Types
Next, the method TryToChangePoint(Point2D p) is called and it copies the value of the variable point to another place in the stack, allocated for the parameter p of the method. When the parameter p is changed in the method's body, it is modified in the stack and does not affect the original variable point that was previously passed as an argument when the method:.
3 point
This is because the variable point will now be passed by reference (not by value) and its value will be shared between point and p in the heap. The figure below illustrates what happens in memory at the end of the method TryToChangePoint(Point2D p) when Point2D is a class:.
Class or Structure?
Point2D@a8fe24
Enumerations
Declaration of Enumerations
Days.cs enum Days
Nature of Enumerations
Hidden Numerical Value of Constants in Enumeration
Coffee.cs public class Coffee
Use of Enumerations
We have three constants for the capacity of the coffee cups in the coffee shop, respectively 100, 150 and 300 ml. Let's rework the method that calculates the price of a cup of coffee depending on the capacity of the cup.
Inner Classes (Nested Classes)
When we try to calculate the coffee price with the new quantity, the method, which calculates the price, will throw an exception, informing the user that such quantity of coffee is not available in the coffee shop. What we need to do to solve this problem is to add a new case condition, which reflects the new constant in the enumerated CoffeeSize type.
Declaration of Inner Classes
When changing the list of constants in an existing enumeration, we must be careful not to break the logic of the code that already exists and uses the constants declared so far. Static members (fields, methods, properties) of the outer class are accessible from the inner class regardless of their access level.
Inner Classes – Example
In the example, the outer class OuterClass defines itself as a member of the class InnerClass. In the example, while the inner class is created, the parent reference is set to the constructor of the outer class.
Usage of Inner Classes
Non-static methods of the inner class have access to their body this as well as to the parent instance of the outer class (via this.parent syntax, if the parent reference is added by the developer).
Car.cs class Car
Declare Enumeration in a Class
Coffee.cs class Coffee
Generics
Shelter for Homeless Animals – Example
Cat.cs public class Cat
Finally, it assigns the number of the last free cell in a used field (steps 4 and 5 of the scheme above). Therefore, we need to copy the AnimalShelter class verbatim and change only the type of objects being handled – Cat.
What Is a Generic Class?
To solve the task effectively, we need to use a function in the C# language that allows us to fulfill all necessary conditions simultaneously. In the following sections, we will introduce the syntax of generic classes, and we will modify our previous example to use generics.
Declaration of Generic Class
If this were our example, we would use the first parameter T to denote Dog objects that our class would work with, and U to denote Cat objects.
Specifying Generic Classes
Using Unknown Types by Declaring Fields
Using Unknown Types in a Method’s Declaration
Typifying (Generics) – Behind the Scenes
Generic Methods
Invokes the method with concrete type (int) Swap
Features by Declaration of Generic Methods in Generic Classes
It should be noted that static methods can also be typed, unlike the class's properties and constructors. So always make sure that there is no overlap of replacements for the unknown types of methods and classes.
Using a Keyword "default" in a Generic Source Code
The error is inside the Release() method and is related to writing a null value to the last released (rightmost) cell in the nest. As we know, the default value for reference type is null, and for numeric types - zero.
Advantages and Disadvantages of Generics
The problem is that we're trying to use a default value for a reference type, but we're not sure if that type is a reference type or a primitive. To deal with this problem, we need to use the default(T) construct instead of null in our code, which returns the default value for the specified type to be used instead of T.
Naming the Parameters of the Generic Types
Exercises
Create the GSMCallHistoryTest class, with which you test the functionality of the GSM class, from task 12, as an object of type GSM. Store the list of elements in a limited-capacity array that is passed as a parameter to the class constructor.
Solutions and Guidelines
Write a function to cancel a fraction (eg if numerator and denominator are 10 and 15 respectively, fraction to be canceled to 2/3).