TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# Ref Parameter

These C# example programs demonstrate the ref keyword on arguments. Ref arguments can be read and written to.

Ref parameters are changed at the calling site.

They are passed as references, not values. This means you can assign the parameter in the called method and have it also be assigned at the calling site.

Example. There is a big difference between ref and out parameters at the language level. Before you can pass a ref parameter, you must assign it to a value. This is for the purpose of definite assignment analysis.

Note: You don't need to assign an out parameter before passing it to a method. The compiler allows this.

But: The out parameter in that method must assign the parameter before returning. This is required.

C# program that uses ref and out

using System;

class Program
{
    static void Main()
    {
	string value1 = "cat"; // Assign string value
	SetString1(ref value1); // Pass as reference parameter
	Console.WriteLine(value1); // Write result

	string value2; // Unassigned string
	SetString2(1, out value2); // Pass as out parameter
	Console.WriteLine(value2); // Write result
    }

    static void SetString1(ref string value)
    {
	if (value == "cat") // Test parameter value
	{
	    Console.WriteLine("Is cat");
	}
	value = "dog"; // Assign parameter to new value
    }

    static void SetString2(int number, out string value)
    {
	if (number == 1) // Check int parameter
	{
	    value = "one"; // Assign out parameter
	}
	else
	{
	    value = "carrot"; // Assign out parameter
	}
    }
}

Output

Is cat
dog
one

The program in the example defines the Program class with the Main entry point and two static methods, SetString1 and SetString2. The methods have formal parameter lists with the reference parameter keywords.

SetString1 has the ref keyword in its method signature. This requires that whenever you pass a string to this method, it must be described with the ref keyword before the identifier.

Then: When the method is called, the storage location of the string variable is copied to the method.

Note: None of the characters pointed to by the string variable are copied. This is important to know for performance work.

SetString2 has the out keyword in its signature. This means that whenever you want to call it, you must describe the string parameter with the out keyword. You do not need to assign the string parameter before sending it to SetString2.

Out

However: You will get a compile-time error if you do not assign the string parameter before any return points.

Compile-Time Error

Definite assignment. The C# language compiler performs a form of static analysis called definite assignment analysis. This is how the compiler proves that each variable is initialized to a value before it is used.

In the example above, the compiler proves ref and out variables are assigned at different points. With ref, definite assignment occurs before the method invocation. With out, it occurs in the method body.

Definite Assignment

Example 2. One usage for ref is to refactor code that acts upon multiple local variables or fields. We create a method with a ref argument. And then we pass each separate variable to this method. This reduces code duplication.

Warning: Using a loop for this pattern may be clearer and faster. If your program happens to use separate fields, though, this can help.

Note: The ref argument in the NullIf method both reads and writes the string. It is an input and output argument.

C# program that uses ref argument

using System;

class Program
{
    static void Main()
    {
	string v1 = "dot";
	string v2 = "net";
	string v3 = "deves";

	NullIf(ref v1);
	NullIf(ref v2);
	NullIf(ref v3);

	Console.WriteLine(v1);
	Console.WriteLine(v2);
	Console.WriteLine(v3);
    }

    static void NullIf(ref string value)
    {
	if (value == "net")
	{
	    value = null;
	}
    }
}

Output

dot

deves

In this program, we could simply repeat the if-statement three times in the Main method. But the NullIf method can instead store that logic in only one place. This program could be written more clearly with an array.

Arrays

Implementation. The difference between ref and out is not in the Common Language Runtime, but is in the C# language itself. In the intermediate language, we find that the ref and out parameters are called with the "string&" type.

Note: The "string" type actually aliases the System.String type in the base class library, so it is not special-cased here.

The FxCop tool will warn you when you use ref and out parameters. It is considered that the best object-oriented design methodologies will return new objects containing fields and properties instead of variable reference parameters.

FxCop

Overload resolution problems. These parameter decorators can confuse the overload resolution step in the C# compiler. For this reason, it is a bad idea to mix ref and out parameters in an interface or object method group.

Overloads

Uses. There are more examples of the out keyword here. Out is sometimes used in methods that enhance performance—it can actually lead to simpler code. But often it makes code more complex and should be avoided.

ParseTryGetValueTester-Doer

Summary. We looked at reference parameter decorators. These keywords allow you to pass variable references, as opposed to object references. The actual storage location of the variable itself is copied on the method invocations.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf