Foreword
This is my sixth study note in my learning journey from nurse to C# developer. Today I learned more about program control and data structures, knowledge that helps me better organize and manage data and flow in programs.
The Continue Statement
The Continue statement is used to immediately end the current loop iteration, evaluate the loop condition, and if true, proceed to the next iteration; otherwise, exit the loop. This reminds me of nursing work where, when a certain step does not apply to a particular patient, we skip that step and continue with the rest of the care plan.
Let me illustrate the use of Continue with an example:
// Simulate ward rounds, skipping empty beds
for (int bedNumber = 1; bedNumber <= 10; bedNumber++)
{
// Assume beds 4 and 7 are empty
if (bedNumber == 4 || bedNumber == 7)
{
Console.WriteLine($"Bed {bedNumber} is empty, skip inspection");
continue; // Skip this iteration and go directly to the next
}
// Execute patient check procedure
Console.WriteLine($"Inspecting patient in bed {bedNumber}");
// Other inspection code...
}
In this example, the loop iterates through bed numbers 1 to 10. When an empty bed (4 or 7) is encountered, the continue statement skips the current loop, does not execute the patient check procedure, and goes directly to the next bed.
Another example is processing patient data:
// Process patient temperature data, skip invalid data
double[] temperatures = { 36.5, 37.2, 0, 36.8, 39.1, 0, 36.9 };
double sum = 0;
int validCount = 0;
for (int i = 0; i < temperatures.Length; i++)
{
// Skip invalid data recorded as 0
if (temperatures[i] == 0)
{
Console.WriteLine($"Temperature data {i+1} is invalid, skip");
continue;
}
// Process valid data
sum += temperatures[i];
validCount++;
Console.WriteLine($"Recorded valid temperature: {temperatures[i]}°C");
}
// Calculate average temperature
double average = sum / validCount;
Console.WriteLine($"Patient average temperature: {average:F1}°C");
In nursing work, the continue statement is like when we execute a series of standard nursing procedures and decide to skip a certain step that is not applicable to a specific patient, directly moving to the next step. This flexibility helps us handle various situations more efficiently.
Ternary Expression
The syntax of the ternary expression is: expression1 ? expression2 : expression3
- Expression1 is usually a relational expression.
- If expression1 is true, expression2 is the value of the entire ternary expression.
- If expression1 is false, expression3 is the value of the entire ternary expression.
Note that the result type of expression2 must be consistent with the result type of expression3, and also consistent with the result type of the entire ternary expression.
Let me illustrate the use of the ternary expression with several examples:
// Example 1: Determine fever based on temperature
double temperature = 37.8;
string result = temperature >= 37.5 ? "Patient has fever" : "Temperature normal";
Console.WriteLine(result); // Output: Patient has fever
The above example is equivalent to the following if-else statement:
double temperature = 37.8;
string result;
if (temperature >= 37.5)
{
result = "Patient has fever";
}
else
{
result = "Temperature normal";
}
Console.WriteLine(result);
As you can see, the ternary expression makes the code more concise.
Let's look at a slightly more complex example:
// Example 2: Return different nursing advice based on blood pressure
int systolicBP = 145; // Systolic blood pressure
string advice = systolicBP >= 140 ?
(systolicBP >= 180 ? "Emergency treatment, lower blood pressure immediately" : "Needs observation, follow medication orders") :
"Blood pressure normal, continue monitoring";
Console.WriteLine(advice); // Output: Needs observation, follow medication orders
In this example, we use a nested ternary expression to handle multiple conditions. When systolic blood pressure exceeds 140, we further judge whether it reaches the emergency level of 180 or above.
Ternary expressions are also useful for calculating values:
// Example 3: Calculate drug dosage (based on weight)
double weight = 65.5; // Patient weight (kg)
double baseDose = 5.0; // Base dose (mg)
double doseMultiplier = weight < 50 ? 0.8 : (weight > 80 ? 1.2 : 1.0);
double finalDose = baseDose * doseMultiplier;
Console.WriteLine($"Patient weight: {weight}kg");
Console.WriteLine($"Dose adjustment factor: {doseMultiplier}");
Console.WriteLine($"Final drug dose: {finalDose}mg");
In my nursing work, similar quick judgment scenarios are common. For example, assigning different nursing levels based on the patient's various indicators, or deciding what measures to take based on assessment results. Ternary expressions help me express these decision-making logic concisely in code.
Anything that can be done with if-else can also be done with ternary expressions. However, when the logic becomes too complex, using traditional if-else may be clearer for code readability.
Constants
The syntax for declaring constants:
const variableType variableName = value
Once a constant is declared, it cannot be reassigned. In nursing, this is similar to some fixed medical parameters, such as normal body temperature range, standard blood pressure values, etc.
Let me illustrate the use of constants with several examples:
// Define medical-related constants
const double NORMAL_BODY_TEMP = 36.5; // Normal body temperature reference value
const int NORMAL_SYSTOLIC_BP = 120; // Normal systolic blood pressure reference value
const int NORMAL_DIASTOLIC_BP = 80; // Normal diastolic blood pressure reference value
const int MIN_ADULT_HEART_RATE = 60; // Minimum adult heart rate
const int MAX_ADULT_HEART_RATE = 100; // Maximum adult heart rate
const string HOSPITAL_NAME = "Ren Ai Hospital"; // Hospital name
// Use constants
double patientTemp = 38.2;
if (patientTemp > NORMAL_BODY_TEMP + 1.0)
{
Console.WriteLine("Patient's temperature is significantly elevated, needs doctor evaluation");
}
int patientSystolicBP = 135;
if (patientSystolicBP > NORMAL_SYSTOLIC_BP)
{
Console.WriteLine("Patient's blood pressure is high");
}
Console.WriteLine($"Welcome to {HOSPITAL_NAME}!");
Constants are typically named in all uppercase letters, with multiple words separated by underscores. This is a common naming convention.
Benefits of constants:
- Improve code readability - use meaningful names instead of magic numbers (e.g., 36.5 instead of body temperature)
- Easy maintenance - if you need to modify a value, you only need to change the constant definition in one place
- Avoid errors - prevents accidental modification of these values in the code
Attempting to reassign a constant causes a compilation error:
const int ADMISSION_AGE = 18;
ADMISSION_AGE = 16; // Compilation error: cannot assign to a constant
In my nursing work, there are many fixed standards and thresholds, such as normal ranges for vital signs, upper limits of medication doses, standard treatment procedures, etc. Using constants in programming reminds me of these medical standards, helping me better understand and remember this concept.
Enums
Enums can standardize our development. The syntax is as follows:
[public] enum EnumName
{
Value1,
Value2,
Value3,
...
}
public is an access modifier, indicating it is publicly accessible from anywhere. The enum name should follow Pascal naming convention. Declare the enum under the namespace and outside the class, meaning all classes in that namespace can use this enum.
An enum is essentially a variable type, similar to int, double, string, decimal, etc., but the way enums are declared, assigned, and used differs from ordinary variable types. We can convert enum type variables to int and string types and vice versa.
Let me illustrate the use of enums with a medical scenario example:
// Define pain level enum for nursing assessment
public enum PainLevel
{
None, // 0 - No pain
Mild, // 1 - Mild pain
Moderate, // 2 - Moderate pain
Severe, // 3 - Severe pain
Unbearable // 4 - Unbearable pain
}
// Define nursing task priority enum
public enum NursingPriority
{
Routine = 1, // Routine nursing
Urgent = 2, // Urgent nursing
Emergency = 3 // Emergency situation
}
// Define patient risk assessment result enum
public enum RiskAssessment
{
Low = 10, // Low risk
Medium = 20, // Medium risk
High = 30 // High risk
}
// Use enums in the program
class Program
{
static void Main(string[] args)
{
// 1. Basic enum usage
PainLevel patientPain = PainLevel.Moderate;
Console.WriteLine($"Patient pain level: {patientPain}"); // Output: Patient pain level: Moderate
// 2. Determine nursing priority based on pain level
NursingPriority priority;
if (patientPain >= PainLevel.Severe)
{
priority = NursingPriority.Urgent;
}
else if (patientPain == PainLevel.None)
{
priority = NursingPriority.Routine;
}
else
{
priority = NursingPriority.Routine;
}
Console.WriteLine($"Nursing priority: {priority}"); // Output: Nursing priority: Routine
// 3. Use enum for decision making
switch (patientPain)
{
case PainLevel.None:
Console.WriteLine("No pain medication needed");
break;
case PainLevel.Mild:
Console.WriteLine("Consider using over-the-counter pain relievers");
break;
case PainLevel.Moderate:
Console.WriteLine("Give oral pain medication as per doctor's orders");
break;
case PainLevel.Severe:
case PainLevel.Unbearable:
Console.WriteLine("Contact doctor immediately, consider injecting pain medication");
break;
default:
Console.WriteLine("Invalid pain assessment");
break;
}
// 4. Convert enum to integer and vice versa
int painValue = (int)patientPain;
Console.WriteLine($"Pain numerical value: {painValue}"); // Output: Pain numerical value: 2
// Convert integer to enum
PainLevel convertedPain = (PainLevel)3;
Console.WriteLine($"Converted pain level: {convertedPain}"); // Output: Converted pain level: Severe
// 5. Convert enum to string
string painString = patientPain.ToString();
Console.WriteLine($"Pain description: {painString}"); // Output: Pain description: Moderate
// 6. Convert string to enum
PainLevel parsedPain = (PainLevel)Enum.Parse(typeof(PainLevel), "Mild");
Console.WriteLine($"Parsed pain level: {parsedPain}"); // Output: Parsed pain level: Mild
// 7. Try converting numeric string
PainLevel numericPain = (PainLevel)Enum.Parse(typeof(PainLevel), "1");
Console.WriteLine($"Numeric parsed pain level: {numericPain}"); // Output: Numeric parsed pain level: Mild
// 8. Handle possible exceptions
try
{
PainLevel invalidPain = (PainLevel)Enum.Parse(typeof(PainLevel), "Critical");
Console.WriteLine($"Parsed result: {invalidPain}");
}
catch (ArgumentException)
{
Console.WriteLine("Cannot convert 'Critical' to a valid pain level because the enum does not contain this value");
}
// 9. Get all possible values of the enum
Console.WriteLine("All possible pain levels:");
foreach (PainLevel level in Enum.GetValues(typeof(PainLevel)))
{
Console.WriteLine($"- {level} ({(int)level})");
}
}
}
In this example, we can see:
- Enum definition: We defined three nursing-related enum types (pain level, nursing priority, and risk assessment)
- Default values: If no value is specified, the first enum member has a value of 0, and subsequent members increment by 1
- Custom values: We can specify custom integer values for enum members, such as
NursingPriorityandRiskAssessment - Enum comparison: Different values of the same enum type can be compared using operators like greater than, equal to, etc.
- Type conversion: Enums can be converted to int and string and vice versa
- Error handling: An exception is thrown when trying to convert a non-existent string to an enum value
In my nursing work, similar grading systems are everywhere. For example:
- Pain assessment scales (0-10)
- Pressure ulcer risk scores (Braden scale)
- Fall risk levels
- Phlebitis grading
- Drug classification systems
Using enums makes the code more standardized and easier to understand, avoiding "magic numbers" (such as directly using 1, 2, 3 without explaining their meanings). At the same time, the compiler also checks type safety, preventing us from misusing enum values.
Structures
Structures help us declare multiple variables of different types at once, usually written under the namespace. The syntax is as follows:
[public] struct StructName (meets Pascal naming)
{
Members; // Fields
}
Unlike variables that can only store one value during program execution, structures can store multiple values. Let me illustrate the use of structures with a nursing scenario example:
// Define vital signs structure for a patient
public struct VitalSigns
{
public double Temperature; // Body temperature
public int HeartRate; // Heart rate
public int SystolicBP; // Systolic blood pressure
public int DiastolicBP; // Diastolic blood pressure
public int RespiratoryRate; // Respiratory rate
public int OxygenSaturation; // Oxygen saturation
}
// Define basic patient information structure
public struct PatientInfo
{
public string Name; // Name
public int Age; // Age
public char Gender; // Gender ('M' or 'F')
public string ID; // Medical record number
public string Ward; // Ward
public int BedNumber; // Bed number
public VitalSigns Vitals; // Vital signs
}
// Example of using structures
class Program
{
static void Main(string[] args)
{
// Create and initialize a patient info
PatientInfo patient;
patient.Name = "Zhang San";
patient.Age = 45;
patient.Gender = 'M';
patient.ID = "P20250305001";
patient.Ward = "Internal Medicine";
patient.BedNumber = 12;
// Set patient vital signs
patient.Vitals.Temperature = 37.2;
patient.Vitals.HeartRate = 78;
patient.Vitals.SystolicBP = 130;
patient.Vitals.DiastolicBP = 85;
patient.Vitals.RespiratoryRate = 16;
patient.Vitals.OxygenSaturation = 98;
// Display patient information
DisplayPatientInfo(patient);
// Assess vital signs
AssessVitalSigns(patient.Vitals);
}
// Method to display patient information
static void DisplayPatientInfo(PatientInfo patient)
{
Console.WriteLine("Patient Basic Information:");
Console.WriteLine($"Name: {patient.Name}");
Console.WriteLine($"Age: {patient.Age} years");
Console.WriteLine($"Gender: {(patient.Gender == 'M' ? "Male" : "Female")}");
Console.WriteLine($"Medical Record No.: {patient.ID}");
Console.WriteLine($"Ward: {patient.Ward}");
Console.WriteLine($"Bed No.: {patient.BedNumber}");
Console.WriteLine("\nVital Signs:");
Console.WriteLine($"Temperature: {patient.Vitals.Temperature}°C");
Console.WriteLine($"Heart Rate: {patient.Vitals.HeartRate} bpm");
Console.WriteLine($"Blood Pressure: {patient.Vitals.SystolicBP}/{patient.Vitals.DiastolicBP} mmHg");
Console.WriteLine($"Respiratory Rate: {patient.Vitals.RespiratoryRate} breaths/min");
Console.WriteLine($"Oxygen Saturation: {patient.Vitals.OxygenSaturation}%");
}
// Method to assess vital signs
static void AssessVitalSigns(VitalSigns vitals)
{
Console.WriteLine("\nVital Signs Assessment:");
// Assess temperature
if (vitals.Temperature > 37.5)
Console.WriteLine("- Temperature is high, needs monitoring");
// Assess heart rate
if (vitals.HeartRate < 60 || vitals.HeartRate > 100)
Console.WriteLine("- Heart rate abnormal, needs attention");
// Assess blood pressure
if (vitals.SystolicBP >= 140 || vitals.DiastolicBP >= 90)
Console.WriteLine("- Blood pressure high, recommend recheck");
// Assess respiratory rate
if (vitals.RespiratoryRate < 12 || vitals.RespiratoryRate > 20)
Console.WriteLine("- Respiratory rate abnormal, needs observation");
// Assess oxygen saturation
if (vitals.OxygenSaturation < 95)
Console.WriteLine("- Oxygen saturation low, consider oxygen therapy");
}
}
In this example, we can see:
- Structure definition: We defined two structures (
VitalSignsandPatientInfo) for storing patient-related information. - Nesting structures: The
PatientInfostructure contains aVitalSignsstructure, demonstrating nested use of structures. - Structure initialization: Shows how to create a structure variable and set its field values.
- Structures as parameters: Shows how to pass a structure as a method parameter.
- Practical application of structures: Through the method to assess vital signs, we demonstrate the practical use of structures.
This way of organizing data reminds me of the medical record system in nursing. In medical records, we also organize various patient information (basic information, vital signs, test results, etc.) in a specific format. Using structures helps us better manage these related data, making the code more organized and maintainable.
Arrays
Arrays allow us to store multiple variables of the same type at once. Syntax:
arrayType[] arrayName = new arrayType[arrayLength]
For example: int[] nums = new int[10];
When I write the above line of code, 10 consecutive spaces are allocated in memory. We call each space an element of the array. To access an element in the array, we need to use the element's index. The index of the last element in the array is length minus one.
Let me illustrate the use of arrays with several nursing work examples:
// Example 1: Record weekly ward patient count
int[] wardPatients = new int[7]; // Create an array of length 7
// Set daily patient numbers
wardPatients[0] = 45; // Monday
wardPatients[1] = 42; // Tuesday
wardPatients[2] = 48; // Wednesday
wardPatients[3] = 50; // Thursday
wardPatients[4] = 47; // Friday
wardPatients[5] = 40; // Saturday
wardPatients[6] = 38; // Sunday
// Calculate average daily patient count
int totalPatients = 0;
for (int i = 0; i < wardPatients.Length; i++)
{
totalPatients += wardPatients[i];
}
double averagePatients = (double)totalPatients / wardPatients.Length;
Console.WriteLine($"Weekly average patient count: {averagePatients:F1}");
// Example 2: Array initialization methods
// Method 1: Direct initialization
double[] temperatures = { 36.5, 36.8, 37.2, 36.9, 37.0 };
// Method 2: New keyword initialization
string[] medications = new string[] { "Penicillin", "Cephalosporin", "Amoxicillin", "Ibuprofen" };
// Method 3: Declare first, then assign
int[] bedNumbers;
bedNumbers = new int[] { 101, 102, 103, 104, 105 };
// Example 3: Two-dimensional array - record temperature records of multiple patients in one day
double[,] patientTemps = new double[3, 4]; // 3 patients, 4 temperature records per day
// Set temperature data
patientTemps[0, 0] = 36.5; // Patient 1 morning
patientTemps[0, 1] = 36.8; // Patient 1 noon
patientTemps[0, 2] = 37.1; // Patient 1 afternoon
patientTemps[0, 3] = 36.9; // Patient 1 evening
// Traverse the two-dimensional array
string[] timeSlots = { "Morning", "Noon", "Afternoon", "Evening" };
for (int patient = 0; patient < 3; patient++)
{
Console.WriteLine($"\nTemperature records for Patient {patient + 1}:");
for (int time = 0; time < 4; time++)
{
Console.WriteLine($"{timeSlots[time]}: {patientTemps[patient, time]}°C");
}
}
// Example 4: Array as method parameter
static double CalculateAverageTemp(double[] temps)
{
double sum = 0;
foreach (double temp in temps)
{
sum += temp;
}
return sum / temps.Length;
}
// Call the method
double[] patient1Temps = { 36.5, 36.8, 37.2, 36.9 };
double avgTemp = CalculateAverageTemp(patient1Temps);
Console.WriteLine($"Patient average temperature: {avgTemp:F1}°C");
// Example 5: Common array operations
string[] nurses = { "Nurse Zhang", "Nurse Li", "Nurse Wang", "Nurse Zhao" };
// Get array length
Console.WriteLine($"Number of nurses: {nurses.Length}");
// Find element
string searchNurse = "Nurse Li";
bool found = Array.IndexOf(nurses, searchNurse) != -1;
Console.WriteLine($"Is {searchNurse} found: {found}");
// Sort array
Array.Sort(nurses);
Console.WriteLine("Sorted nurse list:");
foreach (string nurse in nurses)
{
Console.WriteLine(nurse);
}
// Copy array
string[] backupNurses = new string[nurses.Length];
Array.Copy(nurses, backupNurses, nurses.Length);
In these examples, we can see:
- Creating arrays: Arrays can be created and initialized in multiple ways
- Accessing arrays: Access array elements via index
- Traversing arrays: Use for loops or foreach loops to iterate over arrays
- Two-dimensional arrays: Used to store more complex data structures
- Arrays as parameters: Arrays can be passed as method parameters
- Common array operations: Such as getting length, finding elements, sorting, and copying
Once the length of an array is fixed, it cannot be changed. This reminds me of the medication distribution system in hospitals, where each medication has a fixed storage location and quantity. In nursing work, we often need to handle a set of related data, such as:
- Ward bed numbers
- Patient temperature records
- Medication lists
- Nursing shift schedules
- Vital signs monitoring data
Using arrays can effectively organize and manage these data, making our programs more structured and easier to maintain.
Bubble Sort
Bubble sort is used to arrange the elements in an array in descending or ascending order. For example, for the array:
int[] nums = {9, 8, 7, 6, 5, 4, 3, 2, 1, 0};
Below is a complete bubble sort example that sorts patients by priority:
// Patient priority array (higher number means higher priority)
int[] priorities = { 2, 5, 1, 7, 3, 8, 4, 6 };
string[] patientNames = { "Zhang San", "Li Si", "Wang Wu", "Zhao Liu", "Qian Qi", "Sun Ba", "Zhou Jiu", "Wu Shi" };
Console.WriteLine("Patient priorities before sorting:");
for (int i = 0; i < priorities.Length; i++)
{
Console.WriteLine($"{patientNames[i]}: Priority {priorities[i]}");
}
// Bubble sort (descending)
for (int i = 0; i < priorities.Length - 1; i++)
{
for (int j = 0; j < priorities.Length - 1 - i; j++)
{
// If current element is smaller than the next, swap positions (descending order)
if (priorities[j] < priorities[j + 1])
{
// Swap priorities
int tempPriority = priorities[j];
priorities[j] = priorities[j + 1];
priorities[j + 1] = tempPriority;
// Simultaneously swap corresponding patient names
string tempName = patientNames[j];
patientNames[j] = patientNames[j + 1];
patientNames[j + 1] = tempName;
}
}
}
Console.WriteLine("\nPatient priorities after sorting (descending):");
for (int i = 0; i < priorities.Length; i++)
{
Console.WriteLine($"{i+1}. {patientNames[i]}: Priority {priorities[i]}");
}
This is similar to triaging and treating patients based on priority in nursing work. The idea of bubble sort reminds me of the scenario at the nurse station where we decide which patients to treat first based on the severity of their condition.
Methods
Methods are a mechanism for reusing blocks of code. The syntax is as follows:
[public] static returnType MethodName([parameter list])
{
Method body;
}
Let me illustrate the use of methods with several nursing-related examples:
class NursingProgram
{
// 1. Method with no parameters and no return value
public static void DisplayNursingProtocol()
{
Console.WriteLine("Standard Nursing Procedure:");
Console.WriteLine("1. Measure vital signs");
Console.WriteLine("2. Check infusion status");
Console.WriteLine("3. Observe changes in condition");
Console.WriteLine("4. Record nursing notes");
}
// 2. Method with parameters and return value
public static double CalculateIdealWeight(double height, char gender)
{
// Calculate ideal weight based on height and gender
if (gender == 'M' || gender == 'm')
{
return (height - 100) * 0.9;
}
else
{
return (height - 100) * 0.85;
}
}
// 3. Method with multiple parameters
public static double CalculateBMI(double weight, double height)
{
double heightInMeters = height / 100;
return weight / (heightInMeters * heightInMeters);
}
// 4. Method overloading - evaluate temperature
public static string EvaluateTemperature(double temperature)
{
if (temperature < 35.5) return "Low temperature";
if (temperature <= 37.2) return "Normal";
if (temperature <= 38.0) return "Low-grade fever";
if (temperature <= 39.0) return "Moderate fever";
return "High fever";
}
// Same method name but different parameters
public static string EvaluateTemperature(double temperature, bool isInfant)
{
if (isInfant)
{
// Infant temperature standards are slightly different
if (temperature < 36.0) return "Infant low temperature";
if (temperature <= 37.5) return "Infant normal temperature";
if (temperature <= 38.5) return "Infant low-grade fever";
return "Infant high fever";
}
else
{
return EvaluateTemperature(temperature); // Call another overloaded method
}
}
// 5. Default parameter values
public static string AssessBloodPressure(int systolic, int diastolic, bool detailed = false)
{
string result = "";
if (systolic >= 140 || diastolic >= 90)
{
result = "Blood pressure high";
if (detailed)
{
result += $" (Systolic:{systolic}, Diastolic:{diastolic})";
}
}
else if (systolic < 90 || diastolic < 60)
{
result = "Blood pressure low";
if (detailed)
{
result += $" (Systolic:{systolic}, Diastolic:{diastolic})";
}
}
else
{
result = "Blood pressure normal";
}
return result;
}
// 6. Method using ref parameters
public static void UpdateVitalSigns(ref double temperature, ref int pulse)
{
// Simulate new measured values
temperature = 37.2;
pulse = 75;
}
// Main method using these methods
static void Main(string[] args)
{
// Call method with no parameters
DisplayNursingProtocol();
// Calculate ideal weight
double height = 170;
char gender = 'F';
double idealWeight = CalculateIdealWeight(height, gender);
Console.WriteLine($"\nIdeal weight for a {(gender == 'F' ? "female" : "male")} with height {height}cm: {idealWeight:F1}kg");
// Calculate BMI
double weight = 65;
double bmi = CalculateBMI(weight, height);
Console.WriteLine($"BMI: {bmi:F1}");
// Evaluate temperature using method overloading
double adultTemp = 38.5;
double infantTemp = 37.8;
Console.WriteLine($"\nAdult temperature {adultTemp}°C assessment: {EvaluateTemperature(adultTemp)}");
Console.WriteLine($"Infant temperature {infantTemp}°C assessment: {EvaluateTemperature(infantTemp, true)}");
// Use default parameters
int systolic = 145;
int diastolic = 88;
Console.WriteLine($"\nBlood pressure assessment: {AssessBloodPressure(systolic, diastolic)}");
Console.WriteLine($"Blood pressure assessment (detailed): {AssessBloodPressure(systolic, diastolic, true)}");
// Use ref parameters
double temp = 36.8;
int pulse = 80;
Console.WriteLine($"\nBefore update - Temperature: {temp}°C, Pulse: {pulse} bpm");
UpdateVitalSigns(ref temp, ref pulse);
Console.WriteLine($"After update - Temperature: {temp}°C, Pulse: {pulse} bpm");
}
}
In these examples, we can see:
- Method with no parameters:
DisplayNursingProtocol()shows how to define and use a method without parameters. - Method with parameters and return value:
CalculateIdealWeight()andCalculateBMI()show how to handle input parameters and return calculation results. - Method overloading:
EvaluateTemperature()shows how to provide different parameter versions for the same method name. - Default parameters:
AssessBloodPressure()shows how to use optional parameters. - Reference parameters:
UpdateVitalSigns()shows how to use ref parameters to modify variable values within a method.
These methods remind me of Standard Operating Procedures (SOP) in nursing:
- Each nursing procedure has clear input (e.g., patient condition) and output (e.g., nursing interventions)
- The same nursing procedure may have different variants based on patient type (e.g., adults vs. children)
- Certain nursing operations directly change the patient's state (e.g., medication administration)
- Nursing assessments can have simple and detailed versions
By connecting methods to nursing practice, I find it easier to understand and remember these programming concepts. Methods make our code more organized, just like standardized nursing procedures, improving work efficiency and accuracy.
The Return Statement
The return statement serves two purposes:
- Return the value to be returned from the method.
- Immediately end the execution of the method.
Here is an example using the return statement:
// Evaluate patient temperature status and give nursing advice
static string EvaluateTemperature(double temperature)
{
// Low temperature
if (temperature < 35.5)
{
return "Temperature too low, need to keep warm and monitor";
}
// Normal temperature
if (temperature >= 35.5 && temperature <= 37.2)
{
return "Temperature normal, monitor regularly";
}
// Low-grade fever
if (temperature > 37.2 && temperature <= 38.0)
{
return "Low-grade fever, closely observe";
}
// Moderate fever
if (temperature > 38.0 && temperature <= 39.0)
{
return "Moderate fever, physical cooling and consider medication";
}
// High fever
return "High fever, emergency treatment, notify doctor immediately";
}
// Call in the Main method
static void Main(string[] args)
{
double[] patientTemps = { 36.5, 37.8, 39.2, 35.0, 38.5 };
foreach (double temp in patientTemps)
{
string advice = EvaluateTemperature(temp);
Console.WriteLine($"Temperature {temp}°C: {advice}");
}
}
In this example, once a condition is met, the return statement returns the corresponding advice and immediately ends the method execution, without checking further conditions. This is similar to nursing decision-making: once the patient's condition is determined, take immediate action without considering other possibilities.
Summary
As a nurse turned developer, I find many similarities between programming and nursing work. By connecting these programming concepts with nursing experience, I can better understand and apply this knowledge, gradually growing into a competent C# developer.