Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how-to pass the reference of the current instance in C#

Tags:

c#

reference

e.g. something like ( ref this ) which does not work ... E.g. this fails:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CopyOfThis
{
    class Program
    {
        static void Main(string[] args)
        {
            View objView = new View();
            objView.Boo();
            objView.ShowMsg("The objView.StrVal is " + objView.StrVal);
            Console.Read();
        }
    } //eof Program


    class View
    {
        private string strVal;
        public string StrVal
        {
            get { return strVal; }
            set { strVal = value; } 

        }
        public void Boo()
        {
            Controller objController = new Controller(ref this);
        }

        public void ShowMsg ( string msg ) 
        {
            Console.WriteLine(msg); 
        }


    } //eof class 

    class Controller
    {
        View View { get; set; } 
        public Controller(View objView)
        {
            this.View = objView;
            this.LoadData();
        }

        public void LoadData()
        {
            this.View.StrVal = "newData";
            this.View.ShowMsg("the loaded data is" + this.View.StrVal); 
        }
    } //eof class 

    class Model
    { 

    } //eof class 
} //eof namespace 
like image 365
SamunRashid Avatar asked Jan 12 '10 11:01

SamunRashid


2 Answers

this is already a reference. Code like

DoSomethingWith(this);

is passing the reference to the current object to the method DoSomethingWith.

like image 173
Peter Lillevold Avatar answered Oct 10 '22 19:10

Peter Lillevold


EDIT: Given your edited code example, you don't need to pass ref this since as the accepted answer states - this is already a reference.

you can't pass the this reference by reference because it is constant; passing it by ref would allow it to be changed - which is nonsense as far as C# is concerned.

The closest you can get is to do:

var this2 = this;
foo(ref this2);
like image 27
Andras Zoltan Avatar answered Oct 10 '22 18:10

Andras Zoltan