Overview of Variables

Introduction

In this series of lessons, we will learn how to create graphical applications using the C# language. Our applications will deal with various types of values. To get a value in your application, you can use one of the fundamental data types of C#. Those data types are: char, int, byte, sbyte, short, ushort, uint, nint, nuint, long, ulong, float, double, decimal, and bool. To declare a variable, use one of those types followed by a name for the variable. The declaration must end with a semicolon. Here are examples:

char    gender;
byte    age;
sbyte   temperature;
short   depth;
ushort  gallonsConsumed;
int     depressionRate;
uint    salary;
long    probability;
ulong   yearlyConsumption;
float   rate;
double  distance;
decimal unitPrice;
bool succeeded;

Practical LearningPractical Learning: Introducing Graphical Applications

  1. Start Microsoft Visual Studio 2022
  2. In the Visual Studio 2022 dialog box, click Create a New Project
  3. In the Create a New Project wizard page, in the languages combo box, select C#
  4. In the list of the projects templates, click Console App
  5. Click Next
  6. In the Configure Your New Project dialog box, change the project Name to Exercise3
    Accept or change the project Location
  7. Click Next
  8. In the Framework combo box, select the highest version: .NET 8.0 (Long Term Support)
  9. Click Create
  10. To execute, on the main menu, click Debug -> Start Without Debugging:

    Introduction to Forms

  11. Close the form and return to your programming environment
Author Note

Author Note

If you want, using the form of the application you created, you can apply the descriptions in the following sections to experiment with, and get, the same results.

Introduction to Values

A value is a piece of information you use in your application. To provide this value, when declaring a variable, you can assign a value to the variable. Here are examples:

char    gender = 'm';
byte    age = 88;
sbyte   temperature = -12;
short   depth = -5_247;
ushort  gallonsConsumed = 15_284;
int     depressionRate = -6_048_596;
uint    salary = 226_839;
long    probability = -44039485;
ulong   yearlyConsumption = 660_860_825_068_586;
float   rate = 28.73f;
double  distance = 6_248_646_295d;
decimal unitPrice = 6824.65m;

A Varying Variable

As seen above, you can declare a variable by initializing it. When declaring a variable, if you already have the initial value you want to provide to it, you can declare the variable using the var keyword. Here are examples:

var gender = 'm';
var age = 88;
var temperature = -12;
var depth = -5_247;
var gallonsConsumed = 15_284;
var depressionRate = -6_048_596;
var salary = 226_839;
var probability = -44039485;
var yearlyConsumption = 660_860_825_068_586;
var rate = 28.73f;
var distance = 6_248_646_295d;
var unitPrice = 6824.65m;

A Dynamic Variable

You can also use thee dynamic keyword in place of thee var keyword.

Applications Accessories

Code Comments

A comment is the primary way you document your code. In C#, you start a one-line comment with //. Start a multiline comment with /* and end it with */.

Enumerations

An enumeration is a list of constant integers but each integer is represented by a name. To create an enumeration, use the enum keyword, a name, and curly brackets. In the curly brackets, create a name for each integer. Separate them with comas. Here is an example:

enum Side { Left, Middle, Right }

After creating an enumeration, you can declare a variable of it, but you can initialize the variable only with a member of the enumeration, the member must be accessed by qualifying it from the name of te enumeration. Here is an example:

Side hand = Side.Left;

enum Side { Left, Middle, Right }

Conditional Statements

A Boolean Value

A Boolean value is a value that is True or False. To declare a variable for such a value, use the bool keyword and assign true or false to it. Here is an example:

bool succeeded = false;

You can also declare the variable using the var or the dynamic keyword. Here are examples:

var succeeded = false;

Logical Operators

A logical expression is a comparison of two values to establish their relation. The operators are available: ==, !=, <, <=, >, >=, !, is, and not.

Conditional Expressions

A conditional expression is an expression that evaluates whether something is true or false. The expression combines some keywords and the able logical operators. The available keywords are: if, else, switch, while, do, goto

An Overview of Objects

Introduction to Classes

Our applications will also deal with objects. Before getting an object, you must have a class. To create a class, type class followed by a name and curly brackets. Here is an example:

class Road {}

The section from { to } is the body of the class. In that body, you can add members. For example, you can declare variables and optionally initialize them. Here is an example:

class Road
{
    string name = "I66";
}

A variable declared in a class is called a field.

Access Levels

When creating an item related to an object, you should specify at what level that item can be accessed. The available keywords to provide that information are private, public, internal, and protected. Here are examples that apply two of these keywords:

Side hand = Side.Left;

internal class Road
{
    public string name;
}

public enum Side { Left, Middle, Right }

Creating an Object

After creating a class, the most common way to use it to declare a variable of it. This is also referred to as creating an object. To create an object, type the name of the class, followed by a name for the object. Assign the new operator and parentheses to it. End with a semicolon. Here is an example:

Road rd = new();

internal class Road
{
    public string name;
}

A Dynamically Varying Object

When declaring a variable of a class, you can specify the name of the class between the new operator and the parentheses. This can be done as follows:

Road rd = new Road();

internal class Road { }

When creating an object like that, if you decide to use the name of the class on the right side of the = operator, you can use the var or the dynamic keyword before the name of the object and omit the name of the class. This can be done as follows:

var rd = new Road();

internal class Road { }

The rule is that if you use the name of the class to declare the variable, you can omit the name of the class between the new operator and the parentheses. If you the var or the dynamic keyword to create the object, you must the name of the class between the new operator and the parentheses.

Accessing the Members of a Class

After declaring a variable of a class, you can access the publick and internal members of the class. To do this, type the name of the variable, a period, and the desired member of the class. From there, you can use the member. Here is an example:

var rd = new Road();

rd.name = "I66";

internal class Road
{
    public string name;
}

The Nullity of a Value or Object

Nullifying a Value

When you are declaring a variable, to indicate that it may hold a null value, put a question mark between the data type and the name of the variable.

Nullifying an Object

When creating an object, if you don't yet want to initialize, you must declare the variable using the name of the class and you must assign null to it. Here is an example:

Road rd = null;

internal class Road
{
}

To further indicate that the object is null, precede the namee of the object with a question mark. Here is an example:

Road? rd = null;

internal class Road
{
}

Checking Whether an Object is Null

To check whether an object is null, you can involve it to the is not null expression.

The Methods of a Class

Introduction

A method is a procedure that is created in the body of the class. To create a method, in the body of a class, type an access keyword, a return value, a name for the method, parentheses, and curly brackets. Here is an example:

internal class Road
{
    private void TakeCare()
    {
    }
    
    public string name;
}

Returning a Value from a Method

When creating a method, you may want it to return a value. You must first indicate the return type of the method before its name. In the body of the method, before the closing curly bracket, type the return keyword from the returned value. Here is an example:

public class Calculator
{
    int a;
    int b;
    
    public int Add()
    {
        int result = a + b;

        return result;
    }
}

Calling a Method

Remember that, to access a member of a class, you can first declare a variable of the class. To access a method, type a variable of the class, a period, the method and parenthess. Here is an example:

FoodMenu fm = new FoodMenu();

fm.Prepare();

public class FoodMenu
{
    public void Prepare(){
    }
}

If a method is returning a value, when calling it, you can assign its call to a variable. Here is an example:

Calculator calc = new();

double number = calc.Add();

public class Calculator
{
    int a = 1039;
    int b = 866;

    public double Add(){
        return a + b;
    }
}

The Arguments of a Method

Introduction to Parameters

A parameter is a way to prepare a method to use an external value. To create a parameter, in the parentheses of a method, write a data type and a name. To create more than one parameter, specify the datta type of and the name of each parameter. Separate them with commas. Here are examples:

internal class Calculator
{
    public double DoubleAnInteger(double x)
    {
        double result = x * 2d;

        return result;
    }
    
    public double Add2Numbers(double a, double b)
    {
        double result = a + b;

        return result;
    }
}

Calling a Parameterized Method

When calling a method that uses a parameter, you must provide a value for its parameter or for each parameter. The value you provide is called an argument. Here are examples:

Calculator calc = new();

double x = calc.DoubleANumber(938.227);
double y = calc.Add2Numbers(24.75, 42.50);

internal class Calculator
{
    public double DoubleANumber(double x)
    {
        return x * 2d;
    }
    
    public double Add2Numbers(double a, double b)
    {
        return a + b;
    }
}

Optional Arguments

When creating a parameter for a method, you can make it optional to pass an argument to it when eventually calling it. To do this, when creating the parameter, assign the desired value to the parameter.

The Constructors of a Class

A constructor of a class is a special method that holds the same name as the class but it doesn't return a value. Here is an example of a constructor:

public class Operation
{
    public Operation() {
    
    }
}

As seen with methods, you can overload a constructor. That is, you can create various constructors in a class. Each constructor must difer from the other(s) by the number or types of parameters.

Techniques of Passing Arguments

Passing an Argument IN

When creating a parameter in a method, if you know that you will not change the value of the parameter in the method, you can precede the data type of the parameter with the in keyword. Here are examples:

Calculator calc = new();

double number1 = calc.DoubleANumber(938.227);
double number2 = calc.Add2Numbers(24.75, 42.50);

internal class Calculator
{
    public double DoubleANumber(in double x)
    {
        return x * 2d;
    }
    
    public double Add2Numbers(in double a, in double b)
    {
        return a + b;
    }
}

Passing an Argument by Reference

If you are creating a parameter, you can make the method change the value of the parameter. To do this, precede the data type of the parameter with the ref keyword, both when creating the function or method and when calling it.

Passing a Parameter OUT

Another way to pass a parameter by reference is to mark it as an an "OUT" value.

Properties

Introduction

A property is a piece of information that describes an object. Actually, a property is a member variable that allows one object to exchange data with other objects or values.

Automatic Properties

An automatic property is a member variable that includes a section as { get; set; } Here are two examples of automatic properties:

public class TelevisionShow
{
    public string? SeriesCode { get; set; }
    public string? Category   { get; set; }
}

Staticity

Introduction

A static object or value is one that is not first declared before being used. That is, the object or value is used directly where it is needed. To start, you must create the object as a static one. This is done by using the static keyword.

To create a static field, a state method, or a static property, precede its type with the static keyword. Here are examples:

public class Medication
{
    // A static field
    static string? initial;

    // A regular property
    public int PillCount { get; set; }  

    // A static property
    public static string? Category { get; set; }

    // A static method
    public static void Describe()
    {

    }
}

To create a static class, precede its class keyword with the static keyword. In this case, all the members of the class must be created as static ones. Here is an example:

public static class Courage
{
    public static string? Category { get; set; }

    static Courage()
    {

    }
}

this Object

If you create a non-static class, that class is equipped with a special object named this. You can use that object to access the non-static member of the class from other members of the same class. The this object can also be used like when calling a method.

Inheritance, Polymorphism, and Abstraction

Inheriting from a Class

Imagine you have a good class. Here is an example:

Of course, you can create an object of the class by declaring a variable. Image that some functionally is missing from the class. To increase the efficiency of the class, you can create a new class derived from an existing one. Here is an example:

public class TelevisionShow : NewsBroadcast
{
    public int UsualLengthInMinutes { get; set; }
}

In the same way, you can derive different classes from one clase. Here are examples:

public class Residence
{
    public string? Address      { get; set; }
    public int     Bedrooms     { get; set; }
    public float   Bathrooms    { get; set; }
}

public class Apartment : Residence
{
    public int   MonthlyPayment { get; set; }
}

public class Condominium : Residence
{
    public bool   IndoorGarage  { set; get; }
    public double MarketValue   { get; set; }
}

You can also derive a class from one class, then derive a new class from the second, then derive another class from the new one, etc. This can be done follows:

public class Residence
{
    public string? Address      { get; set; }
    public int     Bedrooms     { get; set; }
    public float   Bathrooms    { get; set; }
}

public class Condominium : Residence
{
    public bool   IndoorGarage  { set; get; }
    public double MarketValue   { get; set; }
}

public class SingleFamily : Condominium
{
    public ubyte  Stories          { set; get; }
    public bool   FinishedBasement { get; set; }
}

You can declare a variable of any of these classes. After creating such an object, you can access only the members of the class whose variable you had declared.

Interfaces

An interface is a list of characteristics and behaviors that an object can have, but those characteristics and behaviors must first be defined by a class. To start, you must create an interface, which is done with the interface keyword, a name that starts with I (this is not a requirement but a strong suggestion), and a body delimited by keurly brackets. In the curly brackets, you can create members, such as properties and methods, without defining them. Here is an example of an interface:

public interface IVehicle
{
    public int NumberOfTires       { get; set; }
    public bool CasTransportPeople { get; set; }
    public bool HasCargo           { get; set; }
}

Before using an interface, you must create at least one class that implements that interface. After doing that, you can declare a variable and initialize it. Here is an example:

IVehicle transporter = new Bus();

transporter.NumberOfTires      = 6;
transporter.CanTransportPeople = true;
transporter.HasCargo           = true;
transporter.Describe();

public interface IVehicle
{
    public int  NumberOfTires      { get; set; }
    public bool CanTransportPeople { get; set; }
    public bool HasCargo           { get; set; }
    public void Describe();

}

public class Bus : IVehicle
{
    private int tires;

    public int NumberOfTires
    {
        get
        {
            if(tires <= 0)
                tires = 1;

            return tires;
        }

        set
        {
            tires = value;
        }
    }
    
    public bool CanTransportPeople { get; set; }
    public bool HasCargo { get; set; }

    public void Describe()
    {
        Console.WriteLine("Vehicle Characteristics");
        Console.WriteLine("-----------------------");
        Console.WriteLine("Number of Tires:     {0}", NumberOfTires);
        Console.WriteLine("Can Transport People {0}", CanTransportPeople);
        Console.WriteLine("Has a Cargo Area:    {0}", HasCargo);
    }
}

This would display:

Vehicle Characteristics
-----------------------
Number of Tires:     6
Can Transport People True
Has a Cargo Area:    True

Press any key to close this window . . .

Virtuality

A virtual member (such as a property or a method) of a class is a member that a class defines but the deriving class(es) are free to provide a new meaning for that member. To create a virtual member, precede it with the virtual keyword. After docing that, you can declare a variable of the class, access, and use the virtual member. Here is an example:

using static System.Console;

Bottle btl = new Bottle();

btl.Material = Material.Glass;
btl.Category = Category.Wine;

WriteLine("Bottle");
WriteLine("------------------------");
WriteLine("Material: " + btl.Material);
WriteLine($"Category:  {btl.Category}");
WriteLine("Capacity: {0} {1}", btl.SpecifyCapacity().measure, btl.SpecifyCapacity().units);
WriteLine("========================");

public enum Category { Water, Beer, Wine, Seed, Miscellaneous }

public enum Material { Glass, Plastic, Aluminium, Other }

public class Bottle
{
    public Category Category { get; set; }
    public Material Material { get; set; }

    public virtual (float measure, string units) SpecifyCapacity()
    {
        if(this.Material == Material.Glass)
            return (0.757f, "liters");

        return (0, "ounces");
    }
}

This would display:

Bottle
------------------------
Material: Glass
Category:  Wine
Capacity: 0.757 liters
========================

Press any key to close this window . . .

Abstraction

An abstract type is one that is prepared in one place but must be defined in another place. For example, you can create an abstract class, but then you must derive at least one class from it. To create an abstract type, precede its name with the abstract keyword. Here is an example:

public abstract class Frog
{

}

An abstract class can have regular types of members, including fields, properties, and methods. An abstract can also have virtual members such as properties and methods, and you can define them.

An abstract class can also have abstract members (properties, methods, etc). If you decide to add an abstract member to a class, you must not define that member, you can provide only its body. Here is an example:

public abstract class Frog
{
    public string? Skin { get; set; }
    public string? LivingRegion { get; set; }

    public virtual (float measure, string units) Size()
    {
        return (0, "inches");
    }

    public abstract string? Introduce();

    protected abstract string? Conclude();
}

After doing this, you must derive a class from the abstract one, and you must implement the abstract members of the parent abstract class.

Overriding a Member of a Class

If you have a class that is based on an abstract class, in that child class, you must define the abstract member(s). To do this, start the body of that member with the override keyword.

Other Types of Objects

Structures

A structure is like a class. It is a technique to create a layout for objects. You create a structure with the struct keyword. Here is an example:

public struct Hand
{

}

In the { and } section, which is the body of the structure, you can add members, such as properties, methods, and constructors. There are many differences between a class and a structure. One is that a structure cannot participate in inheritance: A structure cannot be derived from a structure, except the implicit inheritance from the object type, which applies to all types of any C# application. A structure cannot serve as parent to any class or structure.

Records

Like a class or a structure, a record is a layout of an object. To create a record, use the recrd keyword in place of the class or struct keyword.

Tuples

A tuple of a combination of two or more types of variable grouped into a unit. To have a tuple, create some parentheses in which you enter some elements separated by comas. Each element is created with a type and a name as if declaring a variable. You can then assign some parentheses that contain the values, also separated by comas. Here is an example:

(int number, string name, double salary) = (957_082, "Paul Moto", 26.84d);

You can then access and use the elements of the tuple.

Attributes

An attribute is a statement that suggests to the compiler how it should behave when it reaches a certain section of your code. An attribute is created from a class and that attribute is then applied to a type, such as a class, a property, a method, etc. All the attributes we will need for our lessons have already been created in the .NET Framework and we will simply use them. That is, we will not (need to) create any attribute.

To apply an attribute to a type, precede the type with square brackets []. In the square brackets, enter the attribute or its definition.

Generic Types

A generic value is an object whose type is known only when the object is about to be used. To start, create a function or a class and add <> to its name. Between < and >, type a letter or string that would represent an un undefined type. Here are two examples:

// A function that uses a parameter type
void Cook<T>()
{

}

// A class that uses a parameter type
public class Preparation<T>
{

}

Practical LearningPractical Learning: Ending the Lesson


Previous Copyright © 2001-2024, FunctionX Satuday 06 May 2023, 12:54 Next