0

We are transfering our code from C++ to C# and due to limited knowledge of C# we are stuck into strange situation. Our problem is:

In c++ we have 2-3 types of class/structures which have pointers to property (std::string), purpose of pointer is to make sure that all the instance for similar object will point to same property. e.g

struct st1{
   string strVal;
};
struct st2{
   string* strVal;
};
//At time of creation
st1* objst1 = new st1();
st2* objst2 = new st2();
objst2.strVal = &objst1.strVal;

//After this at all point both object will point to same value.

I want this kind of architecture C#, I got some suggestion like:

  1. Declare events
  2. Make code unsafe and use pointers (but I think this will lead to some other problems)

Please let me know if something better and near to C++ can be done here..

vrajs5
  • 4,066
  • 1
  • 27
  • 44
  • 1
    Unlike std::string, System.String is immutable, and there's usually no point in caring about string references, it's its value that counts. – Felix Ungman Apr 27 '11 at 09:14
  • 1
    You can wrap most of your C++ code into C# directly by using the unmanaged keyword. That being said, for event handling read up on delegates, event handlers, and Func and Action. Lots of that written up here. – Jon Limjap Apr 27 '11 at 09:23

2 Answers2

3

In C# all clases are references / pointers. So as long as your property is of class type, you can have same instance in different structures.

But problem can arise when you use string. While it is class and reference property, it is enforced to be imutable. So when you change it, you dont change the instance itself, but you create new copy with those changes.

One solution that comes to mind is to create custom string class, that will simply contain string and use it as your type:

public class ReferenceString
{
    public String Value { get; set; }
}
Euphoric
  • 12,645
  • 1
  • 30
  • 44
  • 2
    Another option is to use StringBuilder, which is mutable and better corresponds to std::string. – Felix Ungman Apr 27 '11 at 09:21
  • @Felixt : I dont know. Isnt StringBuilder somewhat heavy-weight? And it seems wrong to use such a class as store. But I might be wrong. – Euphoric Apr 27 '11 at 09:26
  • A `StringBuilder` is implemented as a linked list of `char[]` arrays, where each array is no more than 8k chars. This makes inserts very fast and keeps them out of the large-object heap, but makes them less lightweight than a string (which is just an array of chars). – Gabe Apr 27 '11 at 09:40
0

You could use a static property with inheritance:

class thing
{
  static string stringThing;
  public string StringThing
  {
    get { return stringThing; }
    set { stringThing = value; }
  }
}

class thing2 : thing
{
}

Then later:

thing theThing = new thing();
theThing.StringThing = "hello";

thing2 theThing2 = new thing2();
// theThing2.StringThing is "hello"
Dave Arkell
  • 3,920
  • 2
  • 22
  • 27