Create Methods and Parameters, Return Values nd ref and out parameter in C# Programming
How to Create Methods in C# Programming
Introduction to Methods
- The video introduces the concept of methods in C#, explaining their purpose and functionality.
- It emphasizes the importance of understanding method parameters and arguments, as well as how to return values from methods.
Setting Up a C# Project
- The presenter demonstrates creating a project in Microsoft Visual Studio, highlighting that every program starts with a class definition.
- A main function is required within the class, and an example is provided using
Console.WriteLineto display messages.
Creating User Defined Methods
- Methods are defined as blocks of code executed when called; they can be reused throughout the program.
- To create a static method, one must use the
statickeyword followed by the return type and method name. An example function namedSayHellois introduced.
Calling Methods
- The process for calling a method involves simply using its name followed by parentheses. This allows for executing the defined logic within that method.
- When running the program, it outputs "Hello," demonstrating successful execution of the created method.
Understanding Parameters and Arguments
- Parameters are variables that hold incoming data for functions; they allow methods to perform operations based on input values.
- A new example illustrates adding two numbers through a function that takes parameters
AandB, showcasing how these inputs affect output.
Method Definition with Parameters
- The presenter explains how to define a function with parameters for addition, displaying results using
Console.WriteLine.
- When calling this function, specific values (e.g., 10 and 20) must be passed as arguments corresponding to defined parameters.
User Input for Method Parameters
- Instead of hardcoding values into method calls, user input can also be utilized. The presenter suggests prompting users for values of A and B.
Dynamic Programming and Function Return Values
Understanding Parameters and Arguments
- The discussion begins with the introduction of parameters, specifically A and B, which are referred to as arguments when values are passed into a function.
- The speaker illustrates how input values for A (100) and B (24) lead to an output of 124, demonstrating the addition operation performed by the function.
- It is emphasized that variables A and B in the function are local to that scope, meaning they do not share memory with similarly named variables in other scopes.
Performing Operations with Functions
- The speaker notes that various operations such as subtraction or multiplication can be performed using similar methods as addition.
- An explanation follows on how functions can return values instead of just printing them directly.
Returning Values from Methods
- To return a value from a method, one must replace print statements with a return statement that outputs the result of calculations like A + B.
- The importance of matching return types is highlighted; if returning an integer, the method's return type should also be declared as integer rather than void.
Storing and Displaying Returned Values
- After calling the sum function from main, results can be stored in a variable for later use or display.
- The process concludes with an example where inputs 25 and 56 yield an output of 81 after performing addition through returned values.
Call by Value vs. Call by Reference
- The concept of call by value is introduced: passing copies of variables rather than references. This means changes made within functions do not affect original variables outside their scope.
- In contrast, call by reference allows passing memory addresses so modifications within functions impact original data directly.
Example Program for Call by Reference
Understanding Call by Value and Call by Reference in C#
Introduction to Squaring a Number
- The expression for calculating the square of a number is defined as
x = x * x. This can also be achieved using built-in methods likeMath.Sqrt.
Input Handling and Conversion
- User input is taken via
console.write, prompting the user to enter a number, which is stored in variableX. The input string is converted to an integer usingint.Parse.
Function Call and Output Expectations
- After calling the square function with the input value, the expectation is to print the squared result. However, only the original input value (5) is printed instead of its square (25).
Understanding Call by Value
- The output issue arises from "call by value," where a copy of the variable's value is passed to functions. Changes made within the function do not affect the original variable.
- When passing values, modifications inside functions do not reflect on original variables due to separate memory allocation.
Transitioning to Call by Reference
- To modify original values within functions, "call by reference" must be used. This involves passing references (addresses) rather than copies of values.
- Using call by reference allows changes made in functions to directly affect original variables since they share memory space.
Implementing Call by Reference with 'ref' Keyword
- In C#, use the
refkeyword when defining parameters in methods. This passes the address of a variable instead of its value.
- By applying
refbefore both parameter declaration and during method calls, any changes made will impact the original variable directly.
Demonstrating Changes with 'ref'
- If modifications are performed on a referenced variable within a function, those changes will persist outside that function scope due to shared memory.
- Testing this implementation shows that when 5 is passed as input using call by reference, it correctly outputs 25 after squaring.
Exploring Out Parameters
- The discussion transitions into another keyword called
out, which also sends addresses but specifically for output variables. It allows storing intermediate results from methods into different variables.
- Both
refandoutkeywords facilitate passing references; however, whilerefrequires initialization before use,outdoes not necessitate prior assignment.
Banking Operations and Out Parameters in Programming
Creating a Bank Account
- The discussion begins with the need to perform banking operations, specifically creating a method for account balance management, initially set to zero.
- A static method
createAccountis introduced, which requires an initial deposit amount and updates the balance using reference parameters.
- The balance is updated by assigning it the deposited amount when creating an account. This involves calling the method with a reference to the balance variable.
- An example of initializing an account with 500 rupees is provided, demonstrating how this value updates the balance through call-by-reference.
- After updating the balance, a result variable is created to store and display the updated balance using an output parameter.
Utilizing Output Parameters
- The
outkeyword allows storing results from methods; here it’s used to capture updated balances after account creation.
- A console message confirms that an account has been created along with its current balance stored in the result variable.
- It’s emphasized that while balances can be printed directly, they should be protected; hence results are displayed via separate variables instead.
- The application of out parameters enables multiple outputs from a single method call, allowing for efficient data handling without exposing original data directly.
Differences Between Reference and Out Parameters
- Key differences between reference (
ref) and output (out) parameters are highlighted:refrequires initialization before use whileoutdoes not need prior values but must be declared within methods.
- Both types serve different purposes:
refpasses original data whileoutfocuses on returning computed results.
Implementing Deposit Functionality
- A new static method called
depositis introduced where both current balance (passed by reference) and deposit amount are handled similarly as before.
- The deposit operation updates the current balance by adding the deposited amount and stores this new value in another result variable for later use.
Final Outputs After Transactions
- Following account creation, a deposit of 1000 rupees is made. The updated current balance will be displayed using out parameters rather than direct access to ensure encapsulation of data integrity.
- Example outputs show that after creating an account with 500 rupees and depositing 1000 rupees, users see messages confirming their transactions alongside their updated balances.