Hi
How to pass refernces in c#??/
Hi
How to pass refernces in c#??/
private void functionName (ref Type variableName)
{
}
To Call it
functionName(ref variable);
You can pass parameters by reference in C# using this syntax.
public void MyMethod(ref string myString)
{
}
You will then need to put ref before the value when passing it.
Your question is extremely unclear, but it's quite possible that my article on parameter passing in C# will answer whatever you really intended to ask.
In particular, you need to distinguish between passing a reference by value, and passing an argument by reference. If you're hazy on value types and reference types, you might also want to look at my article on that topic.
Calling Code:
string companyName = "New Company";
GetEmail(ref companyName);
Method Code:
private void GetEmail(ref string companyName)
{
}
Your questions isn't clear, but I'd like to point out that in C#, objects are passed by reference by default. Meaning, if you have an object, and then pass that object on to a method that makes changes to that object, those changes will affect the object in your calling code as well, since they both reference the same object.
Jon Skeet has a good article on this here.
In C#, value types (like int, double, byte and structs) are passed by value, by default. This means that the receiving method has a NEW instance of the type. If an int that has a value of 1 is passed to the method, and the method changes it to 2, this change is only reflected within the method, the calling location's int is still 1. If however the ref keyword is added, then changes made to that integer are reflected back to the calling location.
All classes in C# are reference types. This means, by default, the references are passed by value. This is the important part. This means, changes made to that instance of the object are reflected back to the calling location, because it is the same object. However, if the method changes it's reference to a different object, this change is not reflected. In the case you want these changes reflected back, you would need to use the ref keyword on the parameter.
public static void Main()
{
int i = 1;
Method1(i); //i here is still 1
Method2(ref i); //i is now 2
SimpleObj obj = new SimpleObj();
obj.Value = 1;
Method3(obj); //obj.Value now 2
Method4(obj); // obj.Value still 2
Method5(ref obj); //obj.Value now 5
}
private static void Method5(ref SimpleObj obj)
{
obj = new SimpleObj();
obj.Value = 5;
}
private static void Method4(SimpleObj obj)
{
obj = new SimpleObj();
obj.Value = 5;
}
private static void Method3(SimpleObj obj)
{
obj.Value++;
}
private static void Method2(ref int i)
{
i++;
}
private static void Method1(int i)
{
i++;
}
public class SimpleObj
{
public int Value { get; set; }
}
The ref
keyword is covered in section 10.6.1.2 of the C# 3.0 specification. Here is the msdn documentation.