Use of pointer like structure in C# - c#

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:
Declare events
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..

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; }
}

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"

Related

Store a ref value in C# [duplicate]

In C#, is there a way to keep a reference as a member variable in an object (like an object pointer in C++), not just as a parameter?
EDIT: How can I make a pointer or reference to an object as a member variable?
No. Don't forget that the argument could reference a local variable which is out of scope by the time you use the object later on. A couple of options:
Use a mutable wrapper type
Use a delegate which captures the variable instead
Redesign your code to not require this in the first place
It's hard to know which is most suitable without knowing more about what you're trying to achieve, but ref is a dead-end.
If you mean ref the argument passing convention, then no, you cannot store this. From the first note on MSDN:
Do not confuse the concept of passing by reference with the concept of reference types. The two concepts are not the same...
Edit: based on your updated question, C# has different nomenclature about pointers and references. A pointer in C# is an unsafe construct used to somewhat directly reference the memory location of an object. I say somewhat because the memory location can change based on garbage collection (unless you fix it in memory).
References in C# are the default way reference types are passed and stored. They are akin to pointers in other languages, but not quite the same. However, the by-reference argument passing convention allows you to directly change what an object refers to.
If your objective is to keep a mutable reference to a non-reference type local variable, you'll have to encapsulate the local variable in a reference type (like a class). If you could give some sample code, we can give some specific examples.
Yes if it is a reference-type instance. And then it is the only way to store it in another class:
class Bar { }
class Foo
{
private Bar b; // b is a reference to a Bar
}
No if it's about a value-type, or a reference to a reference.
You would see simple object-references everywhere that C++ uses pointers, like in building Trees or Linked-Lists.
class Element { ...; private Element _next; }
For what its worth, you could use an array of size 1 as a reference/pointer. This yields more readable code than creating a new class to wrap a single value type member.
public struct StructWithReferenceMember
{
private int[] intStoredAsReference;
public StructWithReferenceMember(int asValue, int asReference)
: this()
{
IntStoredAsValue = asValue;
intStoredAsReference = new int[] { asReference };
}
public int IntStoredAsValue { get; set; }
public int IntStoredAsReference
{
get { return intStoredAsReference[0]; }
set { intStoredAsReference[0] = value; }
}
}
A similar trick can be used to attempt the highly discouraged practice of using mutable structs.
public class ReferenceProperty<T>
{
private T[] typeReference;
public ReferenceProperty(T value)
{
typeReference = new T[] { value };
}
public T PropertyAsValue
{
get { return typeReference[0]; }
set { typeReference[0] = value; }
}
public T[] PropertyAsReference
{
get { return typeReference; }
}
}
Then use array notation to "dereference" it.
public struct MutableStruct
{
public int member;
public MutableStruct(int value)
{
member = value;
}
}
ReferenceProperty<MutableStruct> referenceToValueType = new ReferenceProperty<MutableStruct>(new MutableStruct(3));
Console.WriteLine("original value: " + referenceToValueType.PropertyAsValue.member.ToString());
//referenceToValueType.PropertyAsValue.member = 4; // compiler error - cannot modify return value because it is not a variable
MutableStruct copyOfStruct = referenceToValueType.PropertyAsReference[0]; // or referenceToValueType.PropertyAsValue
copyOfStruct.member = 4;
Console.WriteLine("original value after modifying copy: " + referenceToValueType.PropertyAsValue.member.ToString());
referenceToValueType.PropertyAsReference[0].member = 5;
Console.WriteLine("original value after modifying reference: " + referenceToValueType.PropertyAsValue.member.ToString());
original value: 3
original value after modifying copy: 3
original value after modifying reference: 5
The way to get the address of a variable is the & operator, similar to C++. Again similarly to C++, you can store the address as a pointer:
class Foo
{
object* _objPtr;
Foo(object obj)
{
unsafe
{
_objPtr = &obj;
}
}
}
Note that any code that uses the address-of operator (&) or pointers must be within a method marked unsafe or within an unsafe code block.
This could be useful if you want to increase performance by not doing array bound-checking for example. The downside (besides safety considerations) is that the assembly must be fully-trusted for it to execute.
As pointed out, in C#, you very rarely actually store pointers, instead you store references so the garbage collector can operate properly. Ensure that you really need pointers in your code before using them!
For more info, see: http://msdn.microsoft.com/en-us/library/y31yhkeb.aspx

How can I persist information about an object after assignment in c#?

I've been asking questions about what I think might be solutions, but somebody pointed out that I'm falling into the XY problem and that I should just ask about my exact problem.
I have a struct that I want other people to be able to use in their own programs. It needs to be possible to implicitly convert to this type from other existing types but at the same time some information needs to persists after this assignment. Here's a simple example of the issue:
using System;
public struct MyStruct {
public string SomethingImportant;
public MyStruct(string s) {
SomethingImportant = s;
}
//this function needs to have no knowledge of how/where the struct is being used
public bool SomeFunction(string s) {
return s == SomethingImportant;
}
public static implicit operator MyStruct(double x) {
return new MyStruct();
}
}
public class MyClass {
MyStruct child = new MyStruct("important");
public MyClass() {
//prints out "important"
Console.WriteLine(child.SomethingImportant);
child = 7.5;
//prints out ""
Console.WriteLine(child.SomethingImportant);
}
}
After the struct is replaced with a new struct from the implicit conversion, the information stored in SomethingImportant is lost. This would be a natural place for overloading the assignment operator but, unfortunately, this isn't possible in c#.
My thoughts turned to attributes because the extra information does not need to be modified after the initial declaration of the object and it would be mostly acceptable if the persistence was restricted to fields of classes. It seems like this isn't a viable option because the struct can't access attributes associated with it unless it knows what type it lives within.
Is there any way to accomplish something remotely like this in c#? I know that adding an explicit update function like MyStruct.Update(double x) would give the desired behavior but, based on how the library functions, this would be a huge burden on users in terms of rewriting large amounts of existing code. I would much rather do something messy, unsafe, or obscure in my own code than require so much rewriting for library users.
Thanks for any thoughts!
I'd say this isn't possible at all, given that "something important" isn't equal for all MyStruct instances (in which case the trivial solution is to make it static).
The implicit conversion creates a new object which cannot know anything about which variable it is assign to, not even if it is assigned at all. So you cannot access any data from that variable.
Perhaps the idea you had with attributes is worth pursuing, that is, moving the tagging one level up in your class hierarchy.
To clarify my point, what is the expected output from this:
public class MyClass
{
public MyClass()
{
MyStruct child1 = new MyStruct( "abc" );
// should print "abc"
Console.WriteLine(child1.SomethingImportant);
MyStruct child2 = 7.5;
// should print out what?
Console.WriteLine(child2.SomethingImportant);
MyStruct child3 = new MyStruct( "cde" );
child3 = 5.7;
// will never, ever print "cde" (if not static)
Console.WriteLine(child2.SomethingImportant);
}
}
but this will work:
public MyOtherClass
{
public MyStruct TheChild;
public string SomethingImportantAssociatedToTheChild;
}
[...]
MyOtherClass a;
a.SomethingImportantAssociatedToTheChild = "abc";
a.TheChild = 7.5;

Object Oriented - Class Variables

I am pretty new to OOP and looking into things in a bit more depth, but I have a bit of confusion between these 3 methods in C# and which one is best and what the differences are between 2 of them.
Example 1
So lets start with this one, which (so I understand) is the wrong way to do it:
public class MyClass
{
public string myAttribute;
}
and in this way I can set the attribute directly using:
myObject.myAttribute = "something";
Example 2
The next way I have seen and that seems to be recomended is this:
public class MyClass
{
public string myAttribute { get; set;}
}
With getters and setters, this where I dont understand the difference between the first 2 as the variable can still be set directly on the object?
Example 3
The third way, and the way that I understand the theory behind, is creating a set function
public class MyClass
{
string myAttribute;
public void setAttribute(string newSetting)
{
myAttribute = newSetting;
//obviously you can apply some logic in here to remove unwanted characters or validate etc.
}
}
So, what are the differences between the three? I assume example 1 is a big no-no so which is best out of 2 and 3, and why use one over the other?
Thanks
The second
public class MyClass
{
public string MyAttribute { get; set;}
}
is basically shorthand for:
public class MyClass
{
private string myPrivateAttribute;
public string MyAttribute
{
get {return myPrivateAttribute;}
set {myPrivateAttribute = value;}
}
}
That is an auto-implemented property, which is exactly the same as any regular property, you just do not have to implement it, when the compiler can do that for you.
So, what is a property? It's nothing more than a couple of methods, coupled with a name. I could do:
public class MyClass
{
private string myPrivateAttribute;
public string GetMyAttribute()
{
return myPrivateAttribute;
}
public void SetMyAttribute(string value)
{
myPrivateAttribute = value;
}
}
but then instead of writing
myClass.MyAttribute = "something";
string variable = myClass.MyAttribute;
I would have to use the more verbose, but not necessarily clearer form:
myClass.SetMyAttribute("something");
string variable = myClass.GetMyAttribute();
Note that nothing constraints the contents of the get and set methods (accessors in C# terminology), they are methods, just like any other. You can add as much or as little logic as you need inside them. I.e. it is useful to make a prototype with auto-implemented properties, and later to add any necessary logic (e.g. log property access, or add lazy initalization) with an explicit implementation.
What your asking here has to do with encapsulation in OOP languages.
The difference between them is in the way you can access the propriety of an object after you created an object from your class.
In the fist example you can access it directly new MyClass().MyAttribute whether you get or set it's value.
In the second example you declare 2 basic functions for accessing it:
public string MyAttribute
{
get {return myPrivateAttribute;}
set {myPrivateAttribute = value;}
}
In the third example you declare your own method for setting the value. This is useful if you want to customize the setter. For example you don't want to set the value passed, but the value multiplied by 2 or something else...
I recommend some reading. You can find something here and here.
Property is a syntactic sugar over private attribute with get and set methods and it's realy helpful and fast to type;
You may treat automatic property with { get; set;} as a public attribute. It has no additional logic but you may add it later without uset ever notice it.
Just exchange
public string MyLine { get; set;}
to
string myLine;
public string MyLine
{
get { return myLine; }
set { myLine = value + Environment.NewLine; }
}
for example if you need so.
You can also easily create read only property as { get; private set }.
So use Properties instead of public attributes every time just because its easier and faster to write and it's provides better encapsulation because user should not be used get and set methods if you decide to use it in new version of yours programm.
One of the main principles of OOP is encapsulation, and this is essentially the difference between the first example and the other 2.
The first example you have a private field which is exposed directly from the object - this is bad because you are allowing mutation of internal data from outside the object and therefore have no control over it.
The other 2 examples are syntactically equivalent, the second being recommended simply because it's less code to write. However, more importantly they both restrict access & control mutation of the internal data so give you complete control over how the data should be managed - this is ecapsulation.

Restricting use of a structure in C#

Ok so lets say I have a structure A like that:
Struct A{
private String _SomeText;
private int _SomeValue;
public A(String someText, int SomeValue) { /*.. set the initial values..*/ }
public String SomeText{ get { return _SomeText; } }
public int SomeValue{ get { return _SomeValue; } }
}
Now what I want to be able to do is to return that Structure A as a result of a method in a Class ABC, like that:
Class ABC{
public A getStructA(){
//creation of Struct A
return a;
}
}
I don't want any programmer using my library (which will have Struct A and Class ABC and some more stuff) to ever be able to create an instance of Struct A.
I want the only way for it to be created is as a return from the getStructA() method. Then the values can be accessed through the appropriate getters.
So is there any way to set a restrictions like that? So a Structure can't be instantiated outside of a certain class? Using C#, .Net4.0.
Thanks for your help.
---EDIT:----
To add some details on why am I trying to achieve this:
My class ABC has some "status" a person can query. This status has 2 string values and then a long list of integers.
There never will be a need to create an object/instance of "Status" by the programmer, the status can only be returned by "getStatus()" function of the class.
I do not want to split these 3 fields to different methods, as to obtain them I am calling Windows API (p/invoke) which returns similar struct with all 3 fields.
If I was indeed going to split it to 3 methods and not use the struct, I would have to either cache results or call the method from Windows API every time one of these 3 methods is called...
So I can either make a public struct and programmers can instantiate it if they want, which will be useless for them as there will be no methods which can accept it as a parameter. Or I can construct the library in such a way that this struct (or change it to a class if it makes things easier) can be obtained only as a return from the method.
If the "restricted" type is a struct, then no, there is no way to do that. The struct must be at least as public as the factory method, and if the struct is public then it can be constructed with its default constructor. However, you can do this:
public struct A
{
private string s;
private int i;
internal bool valid;
internal A(string s, int i)
{
this.s = s;
this.i = i;
this.valid = true;
}
...
and now you can have your library code check the "valid" flag. Instances of A can only be made either (1) by a method internal to your library that can call the internal constructor, or (2) by the default constructor. You can tell them apart with the valid flag.
A number of people have suggested using an interface, but that's a bit pointless; the whole point of using a struct is to get value type semantics and then you go boxing it into an interface. You might as well make it a class in the first place. If it is going to be a class then it is certainly possible to make a factory method; just make all the ctors of the class internal.
And of course I hope it goes without saying that none of this gear should be used to implement code that is resistant to attack by a fully-trusted user. Remember, this system is in place to protect good users from bad code, not good code from bad users. There is nothing whatsoever that stops fully trusted user code from calling whatever private methods they want in your library via reflection, or for that matter, altering the bits inside a struct with unsafe code.
Create a public interface and make the class private to the class invoking it.
public ISpecialReturnType
{
String SomeText{ get; }
int SomeValue{ get; }
}
class ABC{
public ISpecialReturnType getStructA(){
A a = //Get a value for a;
return a;
}
private struct A : ISpecialReturnType
{
private String _SomeText;
private int _SomeValue;
public A(String someText, int SomeValue) { /*.. set the initial values..*/ }
public String SomeText{ get { return _SomeText; } }
public int SomeValue{ get { return _SomeValue; } }
}
}
What exactly are you concerned about? A structure is fundamentally a collection of fields stuck together with duct tape. Since struct assignment copies all of the fields from one struct instance to another, outside the control of the struct type in question, structs have a very limited ability to enforce any sort of invariants, especially in multi-threaded code (unless a struct is exactly 1, 2, or 4 bytes, code that wants to create an instance which contains a mix of data copied from two different instances may do so pretty easily, and there's no way the struct can prevent it).
If you want to ensure that your methods will not accept any instances of a type other than those which your type has produced internally, you should use a class that either has only internal or private constructors. If you do that, you can be certain that you're getting the instances that you yourself produced.
EDIT
Based upon the revisions, I don't think the requested type of restriction is necessary or particularly helpful. It sounds like what's fundamentally desired to stick a bunch of values together and store them into a stuck-together group of variables held by the caller. If you declare a struct as simply:
public struct QueryResult {
public ExecutionDuration as Timespan;
public CompletionTime as DateTime;
public ReturnedMessage as String;
}
then a declaration:
QueryResult foo;
will effectively create three variables, named foo.ExecutionDuration, foo.CompletionTime, and foo.ReturnedMessage. The statement:
foo = queryPerformer.performQuery(...);
will set the values of those three variables according to the results of the function--essentially equivalent to:
{
var temp = queryPerformer.performQuery(...);
foo.ExecutionDuration = temp.ExecutionDuration
foo.CompletionTime = temp.CompletionTime;
foo.ReturnedMessage = temp.ReturnedMessage;
}
Nothing will prevent user code from doing whatever it wants with those three variables, but so what? If user code decides for whatever reason to say foo.ReturnedMessage = "George"; then foo.ReturnedMessage will equal George. The situation is really no different from if code had said:
int functionResult = doSomething();
and then later said functionResult = 43;. The behavior of functionResult, like any other variable, is to hold the last thing written to it. If the last thing written to it is the result of the last call to doSomething(), that's what it will hold. If the last thing written was something else, it will hold something else.
Note that a struct field, unlike a class field or a struct property, can only be changed either by writing to it, or by using a struct assignment statement to write all of the fields in one struct instance with the values in corresponding fields of another. From the consumer's perspective, a read-only struct property carries no such guarantee. A struct may happen to implement a property to behave that way, but without inspecting the code of the property there's no way to know whether the value it returns might be affected by some mutable object.

C# reference member variable

In C#, is there a way to keep a reference as a member variable in an object (like an object pointer in C++), not just as a parameter?
EDIT: How can I make a pointer or reference to an object as a member variable?
No. Don't forget that the argument could reference a local variable which is out of scope by the time you use the object later on. A couple of options:
Use a mutable wrapper type
Use a delegate which captures the variable instead
Redesign your code to not require this in the first place
It's hard to know which is most suitable without knowing more about what you're trying to achieve, but ref is a dead-end.
If you mean ref the argument passing convention, then no, you cannot store this. From the first note on MSDN:
Do not confuse the concept of passing by reference with the concept of reference types. The two concepts are not the same...
Edit: based on your updated question, C# has different nomenclature about pointers and references. A pointer in C# is an unsafe construct used to somewhat directly reference the memory location of an object. I say somewhat because the memory location can change based on garbage collection (unless you fix it in memory).
References in C# are the default way reference types are passed and stored. They are akin to pointers in other languages, but not quite the same. However, the by-reference argument passing convention allows you to directly change what an object refers to.
If your objective is to keep a mutable reference to a non-reference type local variable, you'll have to encapsulate the local variable in a reference type (like a class). If you could give some sample code, we can give some specific examples.
Yes if it is a reference-type instance. And then it is the only way to store it in another class:
class Bar { }
class Foo
{
private Bar b; // b is a reference to a Bar
}
No if it's about a value-type, or a reference to a reference.
You would see simple object-references everywhere that C++ uses pointers, like in building Trees or Linked-Lists.
class Element { ...; private Element _next; }
For what its worth, you could use an array of size 1 as a reference/pointer. This yields more readable code than creating a new class to wrap a single value type member.
public struct StructWithReferenceMember
{
private int[] intStoredAsReference;
public StructWithReferenceMember(int asValue, int asReference)
: this()
{
IntStoredAsValue = asValue;
intStoredAsReference = new int[] { asReference };
}
public int IntStoredAsValue { get; set; }
public int IntStoredAsReference
{
get { return intStoredAsReference[0]; }
set { intStoredAsReference[0] = value; }
}
}
A similar trick can be used to attempt the highly discouraged practice of using mutable structs.
public class ReferenceProperty<T>
{
private T[] typeReference;
public ReferenceProperty(T value)
{
typeReference = new T[] { value };
}
public T PropertyAsValue
{
get { return typeReference[0]; }
set { typeReference[0] = value; }
}
public T[] PropertyAsReference
{
get { return typeReference; }
}
}
Then use array notation to "dereference" it.
public struct MutableStruct
{
public int member;
public MutableStruct(int value)
{
member = value;
}
}
ReferenceProperty<MutableStruct> referenceToValueType = new ReferenceProperty<MutableStruct>(new MutableStruct(3));
Console.WriteLine("original value: " + referenceToValueType.PropertyAsValue.member.ToString());
//referenceToValueType.PropertyAsValue.member = 4; // compiler error - cannot modify return value because it is not a variable
MutableStruct copyOfStruct = referenceToValueType.PropertyAsReference[0]; // or referenceToValueType.PropertyAsValue
copyOfStruct.member = 4;
Console.WriteLine("original value after modifying copy: " + referenceToValueType.PropertyAsValue.member.ToString());
referenceToValueType.PropertyAsReference[0].member = 5;
Console.WriteLine("original value after modifying reference: " + referenceToValueType.PropertyAsValue.member.ToString());
original value: 3
original value after modifying copy: 3
original value after modifying reference: 5
The way to get the address of a variable is the & operator, similar to C++. Again similarly to C++, you can store the address as a pointer:
class Foo
{
object* _objPtr;
Foo(object obj)
{
unsafe
{
_objPtr = &obj;
}
}
}
Note that any code that uses the address-of operator (&) or pointers must be within a method marked unsafe or within an unsafe code block.
This could be useful if you want to increase performance by not doing array bound-checking for example. The downside (besides safety considerations) is that the assembly must be fully-trusted for it to execute.
As pointed out, in C#, you very rarely actually store pointers, instead you store references so the garbage collector can operate properly. Ensure that you really need pointers in your code before using them!
For more info, see: http://msdn.microsoft.com/en-us/library/y31yhkeb.aspx

Categories

Resources