http://www.dotnetperls.com/extension
Program in the above website is modified to work with the Reference Parameter. What changes have to be made to get the Dot net perls output in the Main() method. Problem is highlighted.
using System;
//class ExtensionMethods
//{
// public static string UppercaseFirstLetter(string value)
// {
// //
// // Uppercase the first letter in the string this extension is called on.
// //
// if (value.Length > 0)
// {
// char[] array = value.ToCharArray();
// array[0] = char.ToUpper(array[0]);
// return new string(array);
// }
// return value;
// }
//}
class Program
{
static void Main()
{
//
// Use the string extension method on this value.
//
string value = "dot net perls";
UppercaseFirstLetter(ref value); // Called like an instance method.
Console.WriteLine(value);//Dot net perls
Console.ReadKey();
}
public static void UppercaseFirstLetter(ref string value)
{
//
// Uppercase the first letter in the string this extension is called on.
//
if (value.Length > 0)
{
char[] array = value.ToCharArray();
array[0] = char.ToUpper(array[0]);
string s = new string(array);
Console.WriteLine(s);
//return new string(array);
}
//return value;
}
}
Loading

VulpesPosted Dec 18, 2014, 8:50 AM
using System;
class Program
{
static void Main()
{
string value = "dot net perls";
UppercaseFirstLetter(ref value);
Console.WriteLine(value);//Dot net perls
Console.ReadKey();
}
public static void UppercaseFirstLetter(ref string value)
{
//
// Uppercase the first letter of the string parameter.
//
if (value.Length > 0)
{
char[] array = value.ToCharArray();
array[0] = char.ToUpper(array[0]);
value = new string(array);
}
}
}
The reason why you can't do this is because the 'this' parameter is 'passed by value' and there is no option to 'pass it by reference' instead.
MahaPosted Dec 18, 2014, 8:56 AM