C# Tutorial

C# Tutorial C# First Application C# Variables C# Data Types C# Operators C# Keywords

C# Control Statement

C# If Statements C# Switch Statements C# for Loop C# While Loop C# do While loop C# Jump Statements C# Function C# functions with out variable

C# Arrays

C# Arrays

C# Function

C# Function call by value C# Call by reference C# Passing array to function C# Multidimensional Arrays C# Jagged Arrays C# Params C# Array Class C# Command Line Arguments

C# Object Class

C# Object and Classes C# Constructors C# Destructor C# this Keyword C# static field C# static class C# Static Constructor C# Structs C# enum C# Properties

C# Inheritance

C# Inheritance C# Multilevel Inheritance C# Aggregation C# Member overloading C# Method Overriding C# Base

C# Polymorphism

C# Polymorphism C# Sealed

C# Abstraction

C# Abstraction C# Interface

C# Namespace

C# Namespace C# Access Modifiers C# Encapsulation

C# Strings

C# String

C# Misc

C# Design Patterns Dictionary in C# Boxing and Unboxing in C# Ref and Out in C# Serialization in C# Dispose and Finalize in C# CONSOLE LOG IN C# Get File extension in C# Insert query in c# Difference Between List and Dictionary in C# Getters and Setters in C# Extension Methods in C# Insert query in c# CONSOLE LOG IN C# Get File extension in C# Random.NextDouble() Method in C# Binary Search in C# Difference between Delegates and Interfaces in C# Double.IsFinite() Method in C# Index Constructor in C# Abstraction in C# Basic OOPS Concepts In C# Queue.CopyTo() Method in C# single.compareto() method in C# C# Throw Exception in Constructor DECODE IN C# file.setlastwritetimeutc() method in C# Convert Object to List in C# convert.ToSByte(string, IFormatProvider) Method in C# C# Declare Delegate in Interface console.TreatControl C As Input property in C# Copying the queue elements to 1-D Array in C# Array.Constrainedcopy() Method in C# C# in and out Char.IsLetterOrDigit() method in C# Debugging in C# decimal.compare() method in C# Difference between Console.Read and Console.Readline in C# Metadata in C# C# Event Handler Example Default Interface Methods in C# Difference between hashtable and dictionary in C# C# program to implement IDisposable Interface Encapsulation in C# SortedList.IndexOfVaalue(Object) Method in C# Hash Maps in C# How to clear text files in C# How to Convert xls to xlsx in C# Foreach loop in C# FIFO in C# How to handle null exception in C# Type.Is Instance Of Type() Method in C# How to add data into MySQL database using C# How to use angular js in ASP net Csharp decimal.compare() method in Csharp Difference between Console.Read and Console.Readline in Csharp How to Implement Interface in Csharp char.IsUpper() Method in C# Index Of Any() Method in C# Quantifiers in C# C# program to Get Extension of a Given File C# Error Logging C# ENCRIPTION Can we create an object for Abstract Class in C# Console.CursorVisible in C# SortedDictionary Implementation in C# C# Hash Table with Examples Setting the Location of the Label in c# Collections in c# Virtual Keyword in C# Reverse of string in C# String and StringBuilder in C# Encapsulation in C# SortedList.IndexOfVaalue(Object) Method in C# Hash Maps in C# How to clear text files in C# How to Convert xls to xlsx in C# Foreach loop in C# FIFO in C# How to handle null exception in C# Type.Is Instance Of Type() Method in C# How to add data into MySQL database using C# How to use angular js in ASP net Csharp decimal.compare() method in Csharp Difference between Console.Read and Console.Readline in Csharp How to Implement Interface in Csharp char.IsUpper() Method in C# Index Of Any() Method in C# Quantifiers in C# C# program to Get Extension of a Given File Difference between ref and out in C# Singleton Class in C# Const And Readonly In Csharp BinaryReader and BinaryWriter in C# C# Attributes C# Delegates DirectoryInfo Class in C# Export and Import Excel Data in C# File Class in C# FileInfo Class in C# How to Cancel Parallel Operations in C#? Maximum Degree of Parallelism in C# Parallel Foreach Loop in C# Parallel Invoke in C# StreamReader and StreamWriter in C# TextReader and TextWriter in C# AsQueryable() in C# Basic Database Operations Using C# C# Anonymous Methods C# Events C# Generics C# Indexers C# Multidimensional Indexers C# Multithreading C# New Features C# Overloading of Indexers Difference between delegates and events in C# Operator overloading in C# Filter table in C# C# Queue with Examples C# Sortedlist With Examples C# Stack with Examples C# Unsafe Code File Handling in C# HashSet in C# with Examples List Implementation in C# SortedSet in C# with Examples C# in Depth Delegates and Events in C# Finally Block in C# How to Split String in C# Loggers in C# Nullable Types in C# REVERSE A STRING IN C# TYPE CASTING IN C# What is Generics in C# ABSTRACT CLASS IN C# Application of pointer in C# Await in c# READONLY AND CONSTANT IN C# Type safe in C# Types of Variables in c# Use of delegates in c# ABSTRACT CLASS IN C# Application of pointer in C# Await in c# READONLY AND CONSTANT IN C# Type safe in C# Types of Variables in c# Use of delegates in c# ABSTRACT CLASS IN C# Application of pointer in C# Await in c# READONLY AND CONSTANT IN C# Type safe in C# Types of Variables in c# Use of delegates in c# Atomic Methods Thread Safety and Race Conditions in C# Parallel LINQ in C# Design Principles in C# Difference Between Struct And Class In C# Difference between Abstraction and Encapsulation in C# Escape Sequence Characters in C# What is IOC in C# Multiple Catch blocks in C# Appdomain in C# Call back methods in C# Change Datetime format in C# Declare String array in C# Default Access Specifier in c# Foreach in LINQ C# How to compare two lists in C# How to Convert String to Datetime in c# How to get only Date from DateTime in C# Ispostback in asp net C# JSON OBJECT IN C# JSON STRINGIFY IN C# LAMBDA FUNCTION IN C# LINQ Lambda Expression in C# Microservices in C# MSIL IN C# Reference parameter in C# Shadowing(Method hiding) in C# Solid principles in C# Static Members in C# Task run in C# Transaction scope in C# Type Conversion in c# Unit of Work in C# Unit Test Cases in c# User Defined Exception in c# Using Keyword in C# Var Keyword in C# What is gac in C#

C# in and out

In parameter in C#

To indicate that a method parameter is supplied by reference but cannot be modified by the called method, use the in keyword in C#. This is helpful for parameters that need to be supplied by reference for the calling method to get the results even when they are not changed by the called method.

With the introduction of "in parameter" in C# 7.2, read-only references to variables can now be passed. Before C# 7.2, we passed a variable's references using the "ref" and "out" keywords. "Out" is just intended for output, but "ref" is intended for both input and output. There was, however, no direct choice available if we needed to give a read-only reference—that is, a variable that was passed as input only. For this reason, the term "in parameter" has been introduced in C# 7.2.

Employing a value type variable and the "in" parameter.

using System;

class Program

{

    static void Main(string[] args)

    {

        int p = 23, q = 14, r = 6;

        Console.Write($"{p} + {q} + {r}: ");

        Add(p, q, ref r);

        Console.WriteLine($"{r}");

    }

    public static void Add(ref readonly int a, ref readonly int b, ref int c)

    {

        c = a + b + c;

    }

}

Except for Visual Studio 2017 version 15.5 Preview 1, it will not function with later releases of Visual Studio 2017 version 15.5 or higher versions.

Simply substitute "in" with the keyword "ref read-only" and recompile the code. The code snippet below will appear once "in" has been used instead of "ref read-only."

using System;

class Program

{

    static void Main(string[] args)

    {

        int p = 23, q = 14, r = 6;

        Console.Write($"{p} + {q} + {r}: ");

        Add(p, q, ref r);

        Console.WriteLine($"{r}");

    }

    public static void Add(in int a, in int b, ref int c)

    {

        c = a + b + c;

    }

}

Output:

C# in and out

The compiler can pass a read-only reference to the argument using the in modifier and generate a temporary variable. When an argument needs to be converted, when there is an implicit conversion from the argument type, or when the argument is a value that isn't a variable, the compiler always creates a temporary variable. For instance, when a literal value or the value obtained from a property accessor is used as the argument. Select the read-only modifier ref rather than in if your API requires the argument to be supplied by reference.

Techniques defined with parameters can optimize performance. Large struct-type arguments may be used, and copying those structures comes at a significant cost when functions are invoked within tight loops or important code pathways. Because the called method doesn't change the argument's state, methods declare in parameters that arguments can be supplied by reference securely. You can avoid making the (perhaps) costly copy by passing those parameters via reference. To ensure the argument is provided by reference rather than by value, you must add the in modifier at the call point. The two effects of explicitly utilizing it are as follows:

  • The compiler is forced to choose a method defined with a matching in parameter when an in parameter is specified at the call point. Otherwise, the by-value overload is better when the sole difference between the two methods is the presence of in.
  • By adding in, you indicate that you want to transmit an argument by reference. The place directly referenced must be represented by the argument used within. The same general guidelines hold true for out and ref arguments: Constants, regular properties, and other expressions that yield values are not allowed. If not, the compiler is informed that creating a temporary variable to pass via read-only reference to the method is acceptable by omitting it at the call site. The compiler establishes a temporary variable to get around a few limitations in the arguments:
  • Compile-time constants can be used as parameters in a temporary variable.
  • Properties or alternative expressions for parameters can be used with a temporary variable.
  • When there is an implicit conversion from the argument type to the parameter type, a temporary variable accepts arguments.

Out parameter in C#

In C#, the out keyword is utilized to deliver arguments to methods as a reference type. When a method returns numerous values, it is typically used.

Key Points:

  • Both the method declaration and the calling method must specifically utilize the out keyword to use it as a parameter.
  • Iterator techniques are not permitted to use the out parameters.
  • It's comparable to the ref keyword. However, the primary distinction between the ref and out keywords is that the former requires the variable to be initialized before passing it to the method. However, the variables need not be initialized before being supplied to the method via the out parameter. However, the variable needs to be initialized in the called method before it can return a value to the calling method.
  • Asynchronous methods are not permitted to use the out parameters.
  • The out parameter may be defined inline at the moment the method is called. However, the code block where it calls can also access the inline out parameters.
  • With out parameters, overloading a method is also possible.
  • It is comparable to the in keyword, but ref permits the method that is called it to modify the parameter value while the in keyword does not.
  • Since properties are not variables, they cannot be provided as parameters.
  • C# 6.0, a variable could only pass as an out argument unless the user first declared it. However, starting with C# 7.0, the user can define the out variable in the method call's argument list instead of needing to declare it separately.
  • A method may contain several out parameters.
using System;

class TE {

          // Main method

          static public void Main()

          {

                    //defining a variable

                    // without giving it a value

                    int x;

                    //Variable x is passed to the method

                    //using the out keyword.

                    Add(out x);

                    // Print the value x

                    Console.WriteLine("The value has been added and is: {0}", x);

          }

    //A method where the out parameter is passed in and

    //which returns the passed parameter's value

          public static void Add(out int x)

          {

              x = 15;

                    x += x;

          }

}

Output:

C# in and out

Multiple out parameters:

A method in C# can accept multiple out parameters, which can return numerous values.

Example:

The code below declares two value variables, int x and y, without initializing them. Using the out keyword, we now give these inputs to the Addition method, such as Add(out x, out y);. These variables' values are assigned in the method that they passed.

using System;

class TE {

          // Main method

          static public void Main()

          {

                    // Variable declaration

                    // without value assignment

                    int x, y;

                    // Multiple variables should be passed to the method

                    // using the out keyword.

                    Add(out x, out y);

                    // Display the values x and y

                    Console.WriteLine("The value that has been added is: {0}", x);

                    Console.WriteLine("The value that has been added is: {0}", y);

          }

          // A method where the arguments are passed in

          // and the values of the given

          // parameters are returned

          public static void Add(out int x, out int y)

          {

                    x = 12;

                    y = 45;

                    x += x;

                    y += y;

          }

}

Output:

C# in and out

Improvements to the Out Parameter in C# 7.0:

The following new features have been added to the out parameter in C# 7.0:

  • The term "in-line declaration of out parameter" or "implicit type out parameter" refers to the ability of the out parameter in C# 7.0 to function without the need for declaration and initialization. Its scope is restricted to the local scope or the method body.
  • The method parameter list permits the usage of the var type for the out parameter.
  • It is not required for the name of the out parameter to match in both the definition and the call.
  • It's applicable to Try Pattern as well.

Restrictions on in, out, and reference

  • Async and iterator methods (e.g., yield return and yield break statements) do not support using the in, out, and ref keywords. Furthermore, unless the parameter is a struct, you cannot use the in keyword in the first parameter of an extension method.
  • When determining overloads, it is important to remember that the keywords in, ref, and out are not included in the method signature. Therefore, methods that differ simply in signature concerning these keywords cannot be overloaded.
  • Put another way, your code won't compile if you have two methods with the same name, but one takes an integer as an input parameter, and the other takes an integer as an output parameter.