Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. Pointer in C#

Pointer in C#

Scheduled Pinned Locked Moved C#
questioncsharpc++
18 Posts 9 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • H Offline
    H Offline
    Hamed Musavi
    wrote on last edited by
    #1

    Hi, I want a class to have a pointer to a local variable of another class to change it later. In C++ I do it this way:

    class AClass
    {
    public:
    int *m_pInt;

    AClass(int\* pInt)
    {
      m\_pInt = pInt;
    };
    
    void SomeFunc()
    {
      \*m\_pInt = 20;
    };
    

    };

    class B
    {
    int x;
    AClass a(&x);
    };

    Is it possible to do this in C# using safe types? I'm still new to C#, so excuse me if this is a dumb question.

    "In the end it's a little boy expressing himself."    Yanni

    T C S S A 5 Replies Last reply
    0
    • H Hamed Musavi

      Hi, I want a class to have a pointer to a local variable of another class to change it later. In C++ I do it this way:

      class AClass
      {
      public:
      int *m_pInt;

      AClass(int\* pInt)
      {
        m\_pInt = pInt;
      };
      
      void SomeFunc()
      {
        \*m\_pInt = 20;
      };
      

      };

      class B
      {
      int x;
      AClass a(&x);
      };

      Is it possible to do this in C# using safe types? I'm still new to C#, so excuse me if this is a dumb question.

      "In the end it's a little boy expressing himself."    Yanni

      T Offline
      T Offline
      Thomas Weller 0
      wrote on last edited by
      #2

      There is no such thing as a 'Pointer' in C# - for very good reasons. Yes, what you are trying to do could be done some way or the other. But what is it you are trying to do ? A class should never have access to another classes internal state, this neglects the whole idea of OO programming and encapsulation. Regards Thomas

      www.thomas-weller.de Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the Universe trying to produce bigger and better idiots. So far, the Universe is winning.
      Programmer - an organism that turns coffee into software.

      H realJSOPR 2 Replies Last reply
      0
      • H Hamed Musavi

        Hi, I want a class to have a pointer to a local variable of another class to change it later. In C++ I do it this way:

        class AClass
        {
        public:
        int *m_pInt;

        AClass(int\* pInt)
        {
          m\_pInt = pInt;
        };
        
        void SomeFunc()
        {
          \*m\_pInt = 20;
        };
        

        };

        class B
        {
        int x;
        AClass a(&x);
        };

        Is it possible to do this in C# using safe types? I'm still new to C#, so excuse me if this is a dumb question.

        "In the end it's a little boy expressing himself."    Yanni

        C Offline
        C Offline
        Christian Graus
        wrote on last edited by
        #3

        You can access a pointer in C#, but you almost never need to. Any class is passed by reference, so you can have more than one reference to the one object, as you would with a pointer. An int is a value type, so this does not hold true. You could use int?, I assume that is a class, not a struct (structs are passed by value, not by reference ). The other thing you can do is use delegates to tell clients when a value changes, to get the same effect.

        Christian Graus Driven to the arms of OSX by Vista.

        H N 2 Replies Last reply
        0
        • H Hamed Musavi

          Hi, I want a class to have a pointer to a local variable of another class to change it later. In C++ I do it this way:

          class AClass
          {
          public:
          int *m_pInt;

          AClass(int\* pInt)
          {
            m\_pInt = pInt;
          };
          
          void SomeFunc()
          {
            \*m\_pInt = 20;
          };
          

          };

          class B
          {
          int x;
          AClass a(&x);
          };

          Is it possible to do this in C# using safe types? I'm still new to C#, so excuse me if this is a dumb question.

          "In the end it's a little boy expressing himself."    Yanni

          S Offline
          S Offline
          Simon P Stevens
          wrote on last edited by
          #4

          I agree with Thomas. This is rather ugly design, and totally against all the principles of OO. There are pointers in C#, you just have to use the unsafe[^] keyword before you use them. (And like Thomas say, for good reason, they are not encouraged and can cause lots of problems) In C# types fall into two categories. Value types (structs) and reference types (classes). Reference types are kind of like pointers, when you pass them around, only the reference to the type is passed around and stored on the stack. The actual type is stored once in the heap. You could do this:

          public class AClass
          {
              private BClass \_b;
          
              public AClass(BClass b)
              {
                  \_b = b;
              }
          
              public void SomeFunc()
              {
                  \_b.X = 20;
              }
          }
          
          public class BClass
          {
              private int \_x;
              private AClass \_a;
          
              public BClass()
              {
                  \_a = new AClass(this);
              }
          
              public int X
              {
                  get
                  {
                      return \_x;
                  }
                  set
                  {
                      \_x = value;
                  }
              }
          }
          

          Here, class A holds a reference to the instance of class B, so can call the public property on class B to get/set the value of B's variable.

          Simon

          H 1 Reply Last reply
          0
          • T Thomas Weller 0

            There is no such thing as a 'Pointer' in C# - for very good reasons. Yes, what you are trying to do could be done some way or the other. But what is it you are trying to do ? A class should never have access to another classes internal state, this neglects the whole idea of OO programming and encapsulation. Regards Thomas

            www.thomas-weller.de Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the Universe trying to produce bigger and better idiots. So far, the Universe is winning.
            Programmer - an organism that turns coffee into software.

            H Offline
            H Offline
            Hamed Musavi
            wrote on last edited by
            #5

            Thomas Weller wrote:

            this neglects the whole idea of OO programming and encapsulation

            True. Ironically enough I'm trying to solve a design issue using this method. I'm tired of the large amount of code behind each and every dialog or form due to interactions with controls inside a form. I decided to do this: 1. For each stored procedure of my database I have a set of data that needs to travel between layers of application, so I create an app that generates code for both stored proc and the data it needs or provides. Almost all procedures that work for each table have similar data, so I thought about a class that can hold all data related to each table or a specific task. 2. Most of the time, same data that a sp needs for saving or provides on loading will be shown in a form or gathered to be saved from a form. 3. Instead of using the form to control everything, when instantiating controls, what if I tell them where to store data. I have an instance of the class which is responsible for trnsfering data. It has one member variable for each control. I give access to members of this class to each control. Each control then saves user input in this class instead of holding a local state. 4. Now if I set an object for a button that's responsible for say saving data, I'll give that object my transfer class and it uses the sp class and gives it this transfer class. 5. Now if a new field has to be added later, all I need to do is to modify database and regenerate these classes. The application won't change. UI needs a new control and that control needs an instance of the transfer object or a pointer to it's own variable. Now this maybe not a good way but it's my first attempt to decouple UI classes from a form. I have some new ideas right now that I'm typing these however that might solve previous issue as well. Thanks for the help anyway. :)

            "In the end it's a little boy expressing himself."    Yanni

            T 1 Reply Last reply
            0
            • S Simon P Stevens

              I agree with Thomas. This is rather ugly design, and totally against all the principles of OO. There are pointers in C#, you just have to use the unsafe[^] keyword before you use them. (And like Thomas say, for good reason, they are not encouraged and can cause lots of problems) In C# types fall into two categories. Value types (structs) and reference types (classes). Reference types are kind of like pointers, when you pass them around, only the reference to the type is passed around and stored on the stack. The actual type is stored once in the heap. You could do this:

              public class AClass
              {
                  private BClass \_b;
              
                  public AClass(BClass b)
                  {
                      \_b = b;
                  }
              
                  public void SomeFunc()
                  {
                      \_b.X = 20;
                  }
              }
              
              public class BClass
              {
                  private int \_x;
                  private AClass \_a;
              
                  public BClass()
                  {
                      \_a = new AClass(this);
                  }
              
                  public int X
                  {
                      get
                      {
                          return \_x;
                      }
                      set
                      {
                          \_x = value;
                      }
                  }
              }
              

              Here, class A holds a reference to the instance of class B, so can call the public property on class B to get/set the value of B's variable.

              Simon

              H Offline
              H Offline
              Hamed Musavi
              wrote on last edited by
              #6

              Thank you. Very helpful information. As you mentioned this has a design issue. I'm wondering for a better solution. Thank you again for the helpful information. :)

              "In the end it's a little boy expressing himself."    Yanni

              1 Reply Last reply
              0
              • T Thomas Weller 0

                There is no such thing as a 'Pointer' in C# - for very good reasons. Yes, what you are trying to do could be done some way or the other. But what is it you are trying to do ? A class should never have access to another classes internal state, this neglects the whole idea of OO programming and encapsulation. Regards Thomas

                www.thomas-weller.de Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the Universe trying to produce bigger and better idiots. So far, the Universe is winning.
                Programmer - an organism that turns coffee into software.

                realJSOPR Offline
                realJSOPR Offline
                realJSOP
                wrote on last edited by
                #7

                I think it's more accurate to say that everything in .Net is a pointer.

                "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
                -----
                "...the staggering layers of obscenity in your statement make it a work of art on so many levels." - Jason Jystad, 10/26/2001

                T A 2 Replies Last reply
                0
                • H Hamed Musavi

                  Thomas Weller wrote:

                  this neglects the whole idea of OO programming and encapsulation

                  True. Ironically enough I'm trying to solve a design issue using this method. I'm tired of the large amount of code behind each and every dialog or form due to interactions with controls inside a form. I decided to do this: 1. For each stored procedure of my database I have a set of data that needs to travel between layers of application, so I create an app that generates code for both stored proc and the data it needs or provides. Almost all procedures that work for each table have similar data, so I thought about a class that can hold all data related to each table or a specific task. 2. Most of the time, same data that a sp needs for saving or provides on loading will be shown in a form or gathered to be saved from a form. 3. Instead of using the form to control everything, when instantiating controls, what if I tell them where to store data. I have an instance of the class which is responsible for trnsfering data. It has one member variable for each control. I give access to members of this class to each control. Each control then saves user input in this class instead of holding a local state. 4. Now if I set an object for a button that's responsible for say saving data, I'll give that object my transfer class and it uses the sp class and gives it this transfer class. 5. Now if a new field has to be added later, all I need to do is to modify database and regenerate these classes. The application won't change. UI needs a new control and that control needs an instance of the transfer object or a pointer to it's own variable. Now this maybe not a good way but it's my first attempt to decouple UI classes from a form. I have some new ideas right now that I'm typing these however that might solve previous issue as well. Thanks for the help anyway. :)

                  "In the end it's a little boy expressing himself."    Yanni

                  T Offline
                  T Offline
                  Thomas Weller 0
                  wrote on last edited by
                  #8

                  Wow. If you are quite new to C# this is very ambitious (to say the least). Good luck... Regards Thomas

                  www.thomas-weller.de Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the Universe trying to produce bigger and better idiots. So far, the Universe is winning.
                  Programmer - an organism that turns coffee into software.

                  H 1 Reply Last reply
                  0
                  • T Thomas Weller 0

                    Wow. If you are quite new to C# this is very ambitious (to say the least). Good luck... Regards Thomas

                    www.thomas-weller.de Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the Universe trying to produce bigger and better idiots. So far, the Universe is winning.
                    Programmer - an organism that turns coffee into software.

                    H Offline
                    H Offline
                    Hamed Musavi
                    wrote on last edited by
                    #9

                    It's about a year that I'm new to C#! I never encountered any serious problem unless I wanted something that no one thought of before in Microsoft Visual C# team. I have been coding in C++ for some years mostly in MFC. Now when making a new design I believe language is not much of a problem. This problem existed in MFC and now it exists in MS windows forms. I don't like using events for every task. I just decided to test some new ways of doing that. Most probably someone already did that. Maybe I have been too lazy not to search enough or a bit unlucky(I searched actually.)

                    Thomas Weller wrote:

                    Good luck...

                    Thank you and thanks for the help. :)

                    "In the end it's a little boy expressing himself."    Yanni

                    modified on Wednesday, November 26, 2008 6:11 AM

                    1 Reply Last reply
                    0
                    • realJSOPR realJSOP

                      I think it's more accurate to say that everything in .Net is a pointer.

                      "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
                      -----
                      "...the staggering layers of obscenity in your statement make it a work of art on so many levels." - Jason Jystad, 10/26/2001

                      T Offline
                      T Offline
                      Thomas Weller 0
                      wrote on last edited by
                      #10

                      Well, when you think of a pointer simply as a memory address, then of course you are right. But normally, when programmers say 'pointer', they refer to a concept like the one known from C/C++. And this simply does not exist in .NET (at least not in the safe part of it). (edited to correct a typo...) Regards Thomas

                      www.thomas-weller.de Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the Universe trying to produce bigger and better idiots. So far, the Universe is winning.
                      Programmer - an organism that turns coffee into software.

                      modified on Wednesday, November 26, 2008 5:54 AM

                      1 Reply Last reply
                      0
                      • C Christian Graus

                        You can access a pointer in C#, but you almost never need to. Any class is passed by reference, so you can have more than one reference to the one object, as you would with a pointer. An int is a value type, so this does not hold true. You could use int?, I assume that is a class, not a struct (structs are passed by value, not by reference ). The other thing you can do is use delegates to tell clients when a value changes, to get the same effect.

                        Christian Graus Driven to the arms of OSX by Vista.

                        H Offline
                        H Offline
                        HosamAly
                        wrote on last edited by
                        #11

                        AFAIK, int? is equivalent to NotNullable, which is a struct.

                        My LinkedIn Profile

                        T 1 Reply Last reply
                        0
                        • H HosamAly

                          AFAIK, int? is equivalent to NotNullable, which is a struct.

                          My LinkedIn Profile

                          T Offline
                          T Offline
                          Thomas Weller 0
                          wrote on last edited by
                          #12

                          It's exactly the other way round. The int data type is a value type (i.e. a struct), which means that it is not nullable by design. int? is a syntactical enhancement that is equivalent to Nullable<int>. Regards Thomas

                          www.thomas-weller.de Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the Universe trying to produce bigger and better idiots. So far, the Universe is winning.
                          Programmer - an organism that turns coffee into software.

                          H 1 Reply Last reply
                          0
                          • T Thomas Weller 0

                            It's exactly the other way round. The int data type is a value type (i.e. a struct), which means that it is not nullable by design. int? is a syntactical enhancement that is equivalent to Nullable<int>. Regards Thomas

                            www.thomas-weller.de Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the Universe trying to produce bigger and better idiots. So far, the Universe is winning.
                            Programmer - an organism that turns coffee into software.

                            H Offline
                            H Offline
                            HosamAly
                            wrote on last edited by
                            #13

                            Sorry, I wrote the "Not" by mistake :-O. Nullable<int> is a struct.

                            My LinkedIn Profile

                            1 Reply Last reply
                            0
                            • H Hamed Musavi

                              Hi, I want a class to have a pointer to a local variable of another class to change it later. In C++ I do it this way:

                              class AClass
                              {
                              public:
                              int *m_pInt;

                              AClass(int\* pInt)
                              {
                                m\_pInt = pInt;
                              };
                              
                              void SomeFunc()
                              {
                                \*m\_pInt = 20;
                              };
                              

                              };

                              class B
                              {
                              int x;
                              AClass a(&x);
                              };

                              Is it possible to do this in C# using safe types? I'm still new to C#, so excuse me if this is a dumb question.

                              "In the end it's a little boy expressing himself."    Yanni

                              S Offline
                              S Offline
                              Shyam Bharath
                              wrote on last edited by
                              #14

                              Pass by reference is supported in C# and VB.net. So I guess you can use that. Just search for their sample usage in MSDN

                              ------------------------------------------- It's code that drives you - Shyam

                              H 1 Reply Last reply
                              0
                              • S Shyam Bharath

                                Pass by reference is supported in C# and VB.net. So I guess you can use that. Just search for their sample usage in MSDN

                                ------------------------------------------- It's code that drives you - Shyam

                                H Offline
                                H Offline
                                Hamed Musavi
                                wrote on last edited by
                                #15

                                I know pass by reference. The problem was to hold the reference and change it's value later on. It looks like as I thought it's only possible by wrapping a struct type inside a class and sending reference to that class and using it to access the struct inside or sending a reference to current class that this struct is a member of which is another way of saying same statement. From kind help of others I conclude it this way: To store for later access to a state of another class, we need to have that class. If I was using my brain before asking the question, it was obvious. C# keeps track of references to objects. If someone uses internal data of an object without accessing a reference to that object how can garbage collector find out that it has to keep an object alive even if no one has any reference to that object. No reference = removing it and now a reference to a type inside an object that does not exists is what we ended up. That maybe why we must use class to access it's members. Also as stated earlier it's absolutely a bad design. Thanks for the help anyway.

                                "In the end it's a little boy expressing himself."    Yanni

                                1 Reply Last reply
                                0
                                • C Christian Graus

                                  You can access a pointer in C#, but you almost never need to. Any class is passed by reference, so you can have more than one reference to the one object, as you would with a pointer. An int is a value type, so this does not hold true. You could use int?, I assume that is a class, not a struct (structs are passed by value, not by reference ). The other thing you can do is use delegates to tell clients when a value changes, to get the same effect.

                                  Christian Graus Driven to the arms of OSX by Vista.

                                  N Offline
                                  N Offline
                                  N a v a n e e t h
                                  wrote on last edited by
                                  #16

                                  Christian Graus wrote:

                                  I assume that is a class, not a struct

                                  No. It is a struct[^]

                                  Navaneeth How to use google | Ask smart questions

                                  1 Reply Last reply
                                  0
                                  • realJSOPR realJSOP

                                    I think it's more accurate to say that everything in .Net is a pointer.

                                    "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
                                    -----
                                    "...the staggering layers of obscenity in your statement make it a work of art on so many levels." - Jason Jystad, 10/26/2001

                                    A Offline
                                    A Offline
                                    Alan Balkany
                                    wrote on last edited by
                                    #17

                                    I think that's only true for reference types. Values types (for example) have the actual values pushed onto the stack when passing them as parameters. I think they're handled identically to value types in C++.

                                    1 Reply Last reply
                                    0
                                    • H Hamed Musavi

                                      Hi, I want a class to have a pointer to a local variable of another class to change it later. In C++ I do it this way:

                                      class AClass
                                      {
                                      public:
                                      int *m_pInt;

                                      AClass(int\* pInt)
                                      {
                                        m\_pInt = pInt;
                                      };
                                      
                                      void SomeFunc()
                                      {
                                        \*m\_pInt = 20;
                                      };
                                      

                                      };

                                      class B
                                      {
                                      int x;
                                      AClass a(&x);
                                      };

                                      Is it possible to do this in C# using safe types? I'm still new to C#, so excuse me if this is a dumb question.

                                      "In the end it's a little boy expressing himself."    Yanni

                                      A Offline
                                      A Offline
                                      Alan Balkany
                                      wrote on last edited by
                                      #18

                                      Technically it is possible using boxing (http://www.csharphelp.com/archives/archive100.html[^]). You can use an object for your local variable, and assign any value type to it. If you pass this object as a parameter, its reference (address) is passed, so the called method can change the local variable of your class.

                                      1 Reply Last reply
                                      0
                                      Reply
                                      • Reply as topic
                                      Log in to reply
                                      • Oldest to Newest
                                      • Newest to Oldest
                                      • Most Votes


                                      • Login

                                      • Don't have an account? Register

                                      • Login or register to search.
                                      • First post
                                        Last post
                                      0
                                      • Categories
                                      • Recent
                                      • Tags
                                      • Popular
                                      • World
                                      • Users
                                      • Groups