What is the meaning of "this" in C# - c#

Could anyone please explain the meaning "this" in C#?
Such as:
// complex.cs
using System;
public struct Complex
{
public int real;
public int imaginary;
public Complex(int real, int imaginary)
{
this.real = real;
this.imaginary = imaginary;
}

The this keyword is a reference to the current instance of the class.
In your example, this is used to reference the current instance of the class Complex and it removes the ambiguity between int real in the signature of the constructor vs. the public int real; in the class definition.
MSDN has some documentation on this as well which is worth checking out.
Though not directly related to your question, there is another use of this as the first parameter in extension methods. It is used as the first parameter which signifies the instance to use. If one wanted to add a method to the String class you could simple write in any static class
public static string Left(this string input, int length)
{
// maybe do some error checking if you actually use this
return input.Substring(0, length);
}
See also: http://msdn.microsoft.com/en-us/library/bb383977.aspx

When the body of the method
public Complex(int real, int imaginary) {
this.real = real;
this.imaginary = imaginary;
}
is executing, it is executing on a specific instance of the struct Complex. You can refer to the instance that the code is executing on by using the keyword this. Therefore you can think of the body of the method
public Complex(int real, int imaginary) {
this.real = real;
this.imaginary = imaginary;
}
as reading
public Complex(int real, int imaginary) {
assign the parameter real to the field real for this instance
assign the parameter imaginary to the field imaginary for this instance
}
There is always an implicit this so that the following are equivalent
class Foo {
int foo;
public Foo() {
foo = 17;
}
}
class Foo {
int foo;
public Foo() {
this.foo = 17;
}
}
However, locals take precedence over members so that
class Foo {
int foo;
public Foo(int foo) {
foo = 17;
}
}
assigns 17 so the variable foo that is a parameter to the method. If you want to assign to the instance member when you have a method where there is a local with the same name, you must use this to refer to it.

Nate and d_r_w have the answer. I just want to add that in your code specifically the this. does in deed refere to the member of the CLASS to distinguish from the arguments to the FUNCTION. So, the line
this.real = real
means assign the value of the function (in this case, constructor) parameter 'real' to the class member 'real'. In general you'd use case as well to make the distinction clearer:
public struct Complex
{
public int Real;
public int Imaginary;
public Complex(int real, int imaginary)
{
this.Real = real;
this.Imaginary = imaginary;
}
}

The this keyword refers to the current
instance of the class and is also used
as a modifier of the first parameter
of an extension method.
this (C# reference) - MSDN
C# Keywords - MSDN

this references the instance of the class.

As most answers are mentioning " the current instance of a class", the word "instance" may be difficult for newbies to understand. "the current instance of a class" means the this.varible is specifically used in the class where it is defined, not anywhere else. Therefore, if the variable name also showed up outside of the class, the developer doesn't need to worry about conflicts/confusions brought by using the same variable name multiple times.

this is a variable which represents the current instance of a class. For example
class SampleClass {
public SampleClass(someclass obj) {
obj.sample = this;
}
}
In this example, this is used to set the "sample" property on someclass obj, to the current instance of SampleClass.

Refers to current instance of class

Related

C# how to use the return value in another script

Thank you. suppose I have two scripts.
I get a return value from a method in one script.
public class ClassA {
public int A (int a, int b)
{
return a + b;
}
}
and I want to use the returned value (int A) in another script:
class ClassB {
public ClassA _ClassA = new ClassA();
public int TheReturn;
public void update()
{
TheReturn = _ClassA.A;
}
}
That's how I tried it. And it is not working..
Thank you guys so much for pointing out the lack of argument in TheReturn = _ClassA.A;
If the Input for A is a reading value (a constantly changing value. eg SerialPort.Reading(), instead of int a, int b). And I want to use the actual "return" value from method A of ClassA. What should I do?
Can I use something like print() and then use Read() in another class?
your question is really messi, but maybe this is what you're looking for?
class ClassB
{
public ClassA _ClassA = new ClassA();
public int TheReturn;
public void update(int x, int y)
{
TheReturn = _ClassA.A(x,y);
}
}
Do not think in terms of scripts. For C# it does not matter whether the code is in one file or split among 100 files. This is only an organizational concern.
You have two classes.
ClassA declares a method A with two input parameters and one return value.
If you want to use this method, you first need to create to ClassA object. You are doing so. So far so good.
Then you must call this method and pass the required arguments.
ClassA aObject = new ClassA();
int result;
result = aObject.A(2, 7);
You do so by placing a pair of parentheses after the method name and around the argument list. In this example, the value returned by the method A is stored in the variable result. You could now print it like this
Console.WriteLine(result);
You can also use the result directly instead
Console.WriteLine(aObject.A(2, 7));
in fact, the method call can be part of an expression like
Console.WriteLine(aObject.A(2, 7) * aObject.A(3, 9) + 10);
See: Methods (C# Programming Guide)

Implicit conversions not considered in overload resolution?

I'm trying to wrap a type (outside of my control) so that it would seamlessly appear to implement an interface (also outside of my control).
Given these defintions
// External types. Not changable.
class Foo {
public int I { get; set; }
public int J { get; set; }
}
interface IGenerateSignature {
string Generate();
}
I would like to use a Foo instance to call a method with an IGenerateSignature parameter:
void Test() {
var foo = new Foo { I = 1, J = 2 };
GetSignature(foo);
}
void GetSignature(IGenerateSignature sig) {
Console.Write(sig.Generate());
}
I tried creating an intermediary struct like this:
struct FooSignaturizer : IGenerateSignature {
private readonly Foo _foo;
public FooSignaturizer(Foo f) {
_foo = f;
}
public static implicit operator FooSignaturizer(Foo f) {
return new FooSignaturizer(f);
}
public string Generate() {
return _foo.I + ":" + _foo.J;
}
}
But for some reason overload resolution fails to find the conversion from Foo to FooSignaturizer, and I get a "Cannot convert" compiler error. If I manually add a cast, GetSignature((FooSignaturizer) foo), it works. However, I need to also add support for the Bar and Qux types, with BarSignaturizer and QuxSignaturizer, so the cast won't work for those cases.
Is there a way to accomplish this?
As per 7.5.3.1 of the C# spec, only implicit conversions from argument expression to parameter type are considered.
7.5.3.1 Applicable function member
A function member is said to be an applicable function member with respect to an argument list A when all of the following are true:
Each argument in A corresponds to a parameter in the function member declaration as described in §7.5.1.1, and any parameter to which no argument corresponds is an optional parameter.
For each argument in A, the parameter passing mode of the argument (i.e., value, ref, or out) is identical to the parameter passing mode of the corresponding parameter, and
for a value parameter or a parameter array, an implicit conversion (§6.1) exists from the argument to the type of the corresponding parameter, or
for a ref or out parameter, the type of the argument is identical to the type of the corresponding parameter. After all, a ref or out parameter is an alias for the argument passed.
What you have here isn't an implicit conversion from Foo to IGenereateSignature, it's a wrapper.
As an explanation for this behaviour, you can't exect the compiler to go though every implementation of IGenerateSignature in scope to see whether it has an implicit conversion to/from Foo. What if there was more than one?
In terms of how you can achieve this for Foo, Bar and Qux...
What you're trying to achieve, one call to GetSignature(fooOrBarOrQux), isn't possible, because (based on your description of Foo) you can't have one variable that can be a Foo or a Bar or a Qux at compile time - they're unrelated. You'll always need three call sites, so there's no reason not to have three slightly-different conversions (wrapper class or overloaded method call or something) for the three cases.
... unless you use dynamic?
Rawling's answer gives a good explanation of why you have the problem. Since you can't fix this with implicit conversion, you could try extension methods to convert all types to IGenerateSignature like this:
void Test() {
var foo = new Foo { I = 1, J = 2 };
GetSignature(foo.AsIGenerateSignature());
}
void GetSignature(IGenerateSignature sig) {
Console.Write(sig.Generate());
}
public static class GenerateSignatureExtensions
{
public static IGenerateSignature AsIGenerateSignature(this IGenerateSignature me)
{
return me;
}
public static IGenerateSignature AsIGenerateSignature(this Foo me)
{
return new FooSignaturizer(me);
}
public static IGenerateSignature AsIGenerateSignature(this Bar me)
{
return new BarSignaturizer(me);
}
//....
}
Rawling's answer gives a great explanation of the why you are having a problem. As to how to achieve what you want. I might consider something like this:
public interface ISignaturizer
{
IGenerateSignature ToSignaturizer();
}
struct FooSignaturizer : IGenerateSignature, ISignaturizer{
private readonly Foo _foo;
public FooSignaturizer(Foo f) {
_foo = f;
}
public string Generate() {
return _foo.I + ":" + _foo.J;
}
public IGenerateSignature ToSignaturizer()
{
return (IGenerateSignature)this;
}
}
Now BarSignaturizer and QuxSignaturizer can implement the same interface. And then you can do:
GetSignature(((ISignaturizer)fooOrBarOrQux).ToSignaturizer());
Which isn't quite as elegant, but I think should accomplish what you need.

Explicitly refer to a parameter

How do I explicitly refer to the parameter as opposed to the member variable?
static recursive{
public static List<string> output = new List<string>();
public static void Recursive(List<string> output){
...
}
}
An unqualified reference will always refer to the parameter because it is at a more local scope.
If you want to refer to the member variable, you need to qualify it with the name of the class (or this, for non-static member variables).
output = foo; // refers to the parameter
recursive.output = foo; // refers to a static member variable
this.output = foo; // refers to a non-static member variable
But you should probably change the name anyway. It makes your code much easier to read.
And you shouldn't have public static variables at all. All of the .NET coding style guidelines strongly recommend properties instead of exposing public fields. And since those are always camel-cased, this problem solves itself.
public static void Recursive(List<string> output){
...
}
The code in the block that refers to output will always be local & not the member variable.
If you wish to refer to member variable, you could use recursive.output.
When you are inside the Recursive static method output will point to the argument of the method. If you want to point to the static field use the name of the static class as prefix: recursive.output
Give your member variable another name.
The convention is to use Camelcasing on public static members.
public static List<string> Output = new List<string>();
public static void Recursive( List<string> output )
{
Output = output;
}
You can explicitly reference recursive.output to indicate the static member, but it would be cleaner to rename either the parameter or the member.
I know of no way to explicitly refer to a parameter. The way this is usually handled is to give member variables a special prefix such as _ or m_ so that parameters will never have exactly the same name. The other way is to refer to member variables using this.var.
public class MyClass {
public int number = 15;
public void DoSomething(int number) {
Console.WriteLine(this.number); // prints value of "MyClass.number"
Console.WriteLine(number); // prints value of "number" parameter
}
}
EDIT::
For static fields is required name of class instead of "this":
public class MyClass {
public static int number = 15;
public void DoSomething(int number) {
Console.WriteLine(this.number); // prints value of "MyClass.number"
Console.WriteLine(MyClass.number); // prints value of "number" parameter
}
}

How do I assign by "reference" to a class field in C#?

I am trying to understand how to assign by "reference" to a class field in C#.
I have the following example to consider:
public class X
{
public X()
{
string example = "X";
new Y(ref example);
new Z(ref example);
System.Diagnostics.Debug.WriteLine(example);
}
}
public class Y
{
public Y( ref string example )
{
example += " (Updated By Y)";
}
}
public class Z
{
private string _Example;
public Z(ref string example)
{
this._Example = example;
this._Example += " (Updated By Z)";
}
}
var x = new X();
When running the above code the output is:
X (Updated By Y)
And not:
X (Updated By Y) (Updated By Z)
As I had hoped.
It seems that assigning a "ref parameter" to a field loses the reference.
Is there a way to keep hold of the reference when assigning to a field?
As others have noted, you cannot have a field of "ref to variable" type. However, just knowing that you cannot do it is probably unsatisfying; you probably also want to know first, why not, and second, how to get around this restriction.
The reason why is because there are only three possibilities:
1) Disallow fields of ref type
2) Allow unsafe fields of ref type
3) Do not use the temporary storage pool for local variables (aka "the stack")
Suppose we allowed fields of ref type. Then you could do
public ref int x;
void M()
{
int y = 123;
this.x = ref y;
}
and now y can be accessed after M completes. This means that either we're in case (2) -- accessing this.x will crash and die horribly because the storage for y no longer exists -- or we're in case (3), and the local y is stored on the garbage collected heap, not the temporary memory pool.
We like the optimization that local variables be stored on the temporary pool even if they are being passed by ref, and we hate the idea that you could leave a time bomb around that could make your program crash and die later. Therefore, option one it is: no ref fields.
Note that for local variables that are closed-over variables of anonymous functions we choose option (3); those local variables are not allocated out of the temporary pool.
Which then brings us to the second question: how do you get around it? If the reason you want a ref field is to make a getter and setter of another variable, that's perfectly legal:
sealed class Ref<T>
{
private readonly Func<T> getter;
private readonly Action<T> setter;
public Ref(Func<T> getter, Action<T> setter)
{
this.getter = getter;
this.setter = setter;
}
public T Value { get { return getter(); } set { setter(value); } }
}
...
Ref<int> x;
void M()
{
int y = 123;
x = new Ref<int>(()=>y, z=>{y=z;});
x.Value = 456;
Console.WriteLine(y); // 456 -- setting x.Value changes y.
}
And there you go. y is stored on the gc heap, and x is an object that has the ability to get and set y.
Note that the CLR does support ref locals and ref returning methods, though C# does not. Perhaps a hypothetical future version of C# will support these features; I have prototyped it and it works well. However, this is not real high on the priority list, so I wouldn't get my hopes up.
UPDATE: The feature mentioned in the paragraph above was finally implemented for real in C# 7. However, you still cannot store a ref in a field.
No. ref is purely a calling convention. You can't use it to qualify a field. In Z, _Example gets set to the value of the string reference passed in. You then assign a new string reference to it using +=. You never assign to example, so the ref has no effect.
The only work-around for what you want is to have a shared mutable wrapper object (an array or a hypothetical StringWrapper) that contains the reference (a string here). Generally, if you need this, you can find a larger mutable object for the classes to share.
public class StringWrapper
{
public string s;
public StringWrapper(string s)
{
this.s = s;
}
public string ToString()
{
return s;
}
}
public class X
{
public X()
{
StringWrapper example = new StringWrapper("X");
new Z(example)
System.Diagnostics.Debug.WriteLine( example );
}
}
public class Z
{
private StringWrapper _Example;
public Z( StringWrapper example )
{
this._Example = example;
this._Example.s += " (Updated By Z)";
}
}
You forgot to update the reference in the Z class:
public class Z {
private string _Example;
public Z(ref string example) {
example = this._Example += " (Updated By Z)";
}
}
Output: X (Updated By Y) (Updated By Z)
Point to keep in mind is that the += operator for a string calls the String.Concat() method. Which creates a new string object, it doesn't update the value of a string. String objects are immutable, the string class doesn't have any methods or fields that lets you change the value. Very different from the default behavior of a regular reference type.
So if you use a string method or operator, you always have to assign the return value back to a variable. This is pretty natural syntax, value types behave the same way. Your code would be very similar if you used an int instead of a string.

Store a reference to a value type?

I am writing a "Monitor" object to facilitate debugging of my app. This Monitor object can be accessed at run time from an IronPython interpreter. My question is, is it possible in C# to store a reference to a value type? Say I have the following class:
class Test
{
public int a;
}
Can I somehow store a "pointer" to "a" in order to be able to check it's value anytime? Is it possible using safe and managed code?
Thanks.
You cannot store a reference to a variable in a field or array. The CLR requires that a reference to a variable be in (1) a formal parameter, (2) a local, or (3) the return type of a method. C# supports (1) but not the other two.
(ASIDE: It is possible for C# to support the other two; in fact I have written a prototype compiler that does implement those features. It's pretty neat. (See http://ericlippert.com/2011/06/23/ref-returns-and-ref-locals/ for details.) Of course one has to write an algorithm that verifies that no ref local could possibly be referring to a local that was on a now-destroyed stack frame, which gets a bit tricky, but its doable. Perhaps we will support this in a hypothetical future version of the language. (UPDATE: It was added to C# 7!))
However, you can make a variable have arbitrarily long lifetime, by putting it in a field or array. If what you need is a "reference" in the sense of "I need to store an alias to an arbitrary variable", then, no. But if what you need is a reference in the sense of "I need a magic token that lets me read and write a particular variable", then just use a delegate, or a pair of delegates.
sealed class Ref<T>
{
private Func<T> getter;
private Action<T> setter;
public Ref(Func<T> getter, Action<T> setter)
{
this.getter = getter;
this.setter = setter;
}
public T Value
{
get { return getter(); }
set { setter(value); }
}
}
...
Ref<string> M()
{
string x = "hello";
Ref<string> rx = new Ref<string>(()=>x, v=>{x=v;});
rx.Value = "goodbye";
Console.WriteLine(x); // goodbye
return rx;
}
The outer local variable x will stay alive at least until rx is reclaimed.
No - you can't store a "pointer" to a value type directly in C#.
Typically, you'd hold a reference to the Test instance containing "a" - this gives you access to a (via testInstance.a).
Here is a pattern I came up with that I find myself using quite a bit. Usually in the case of passing properties as parameters for use on any object of the parent type, but it works just as well for a single instance. (doesn't work for local scope value types tho)
public interface IValuePointer<T>
{
T Value { get; set; }
}
public class ValuePointer<TParent, TType> : IValuePointer<TType>
{
private readonly TParent _instance;
private readonly Func<TParent, TType> _propertyExpression;
private readonly PropertyInfo _propInfo;
private readonly FieldInfo _fieldInfo;
public ValuePointer(TParent instance,
Expression<Func<TParent, TType>> propertyExpression)
{
_instance = instance;
_propertyExpression = propertyExpression.Compile();
_propInfo = ((MemberExpression)(propertyExpression).Body).Member as PropertyInfo;
_fieldInfo = ((MemberExpression)(propertyExpression).Body).Member as FieldInfo;
}
public TType Value
{
get { return _propertyExpression.Invoke(_instance); }
set
{
if (_fieldInfo != null)
{
_fieldInfo.SetValue(_instance, value);
return;
}
_propInfo.SetValue(_instance, value, null);
}
}
}
This can then be used like so
class Test
{
public int a;
}
void Main()
{
Test testInstance = new Test();
var pointer = new ValuePointer(testInstance,x=> x.a);
testInstance.a = 5;
int copyOfValue = pointer.Value;
pointer.Value = 6;
}
Notice the interface with a more limited set of template arguments, this allows you to pass the pointer to something that has no knowledge of the parent type.
You could even implement another interface with no template arguments that calls .ToString on any value type (don't forget the null check first)
You can create ref-return delegate. This is similar to Erik's solution, except instead of getter and setter it use single ref-returning delegate.
You can't use it with properties or local variables, but it returns true reference (not just copy).
public delegate ref T Ref<T>();
class Test
{
public int a;
}
static Ref<int> M()
{
Test t = new Test();
t.a = 10;
Ref<int> rx = () => ref t.a;
rx() = 5;
Console.WriteLine(t.a); // 5
return rx;
}
You can literally take a pointer to a value type using usafe code
public class Foo
{
public int a;
}
unsafe static class Program
{
static void Main(string[] args)
{
var f=new Foo() { a=1 };
// f.a = 1
fixed(int* ptr=&f.a)
{
*ptr=2;
}
// f.a = 2
}
}
class Test
{
private int a;
/// <summary>
/// points to my variable type interger,
/// where the identifier is named 'a'.
/// </summary>
public int A
{
get { return a; }
set { a = value; }
}
}
Why put yourself through all that hassle of writing complicated code, declaring identifiers everywhere linking to the same location? Make a property, add some XML code to help you outside the class, and use the properties in your coding.
I don't know about storing a pointer, don't think it's possible, but if you're just wanting to check its value, the safest way to my knowledge is to create a property of the variable. At least that way you can check its property at any time and if the variable is static, you wouldn't even have to create an instance of the class to access the variable.
Properties have a lot of advantages; type safety is one, XML tags another. Start using them!

Categories