Reputation: 3459
I've been using something similar to this whenever I needed to reference a Value type:
public class RefHost<T> {
public RefHost(T val)
{
Value = val;
}
private T _value;
public T Value {
get {
return _value;
}
set {
_value = value;
}
}
}
What I'm wondering is there a built in way or an easier way to use an existing Value type as a Reference type?
Example:
public class Editor {
public RefHost<int> Blah = new RefHost<int>(5);
// Some kind of timer to increase the value of Blah every few ticks
}
Kind of like that where the user of Editor
specifies a value type that needs to be changed, and there can be multiple instances of Editor
each with it's own value. I used the timer as an example but most of the time it's a user control like a slider.
Upvotes: 0
Views: 145
Reputation: 81143
Replace the property and backing field with a public field. While it is generally good for classes to use properties rather than fields, the whole purpose of your type is to be a simple mutable container for a single value-type instance; the state encapsulated by any reference to an instance of the type should be precisely defined by two things:
If two instances have the same Value
, and if within the entire universe only one reference exists to each one, the two references should be semantically indistinguishable [since in both cases the set of "other references" that exist to the instances would be empty]
While there are various helper methods that a type of that style might implement, it would be impossible for a future version of the type to add additional state without violating the expected semantics. Since the whole purpose of the type is to behave like a class object containing a single field of type T
, code will be clearest if one writes the object to in fact be a class object containing a single field of type T
.
BTW, if you don't want to define a custom type, another option is to use a single-element T[1]
. That will use a little bit of extra storage to hold the dimension, and adding [0]
to all references will be a little uglier than .Value
, but such an approach will nonetheless work pretty simply.
Upvotes: 0
Reputation: 6424
Boxing and unboxing is what this is called. Your solution might be more type safe though.
See http://msdn.microsoft.com/en-us/library/yz2be5wk.aspx
Upvotes: 0
Reputation: 56536
What's wrong with this?
public class Editor {
public int Blah = 5;
// Some kind of timer, with a handler like:
void MyTimerTicker(object sender, EventArgs e)
{
this.Blah += 1;
}
}
Upvotes: 1
Reputation: 22794
Sure there is. If you want to pass it as a reference type to a method just use the ref
modifier:
public static void Main()
{
int n = 1;
Test(ref n);
Console.WriteLine(n); //will print out 2 and not 1.
Console.ReadKey(true);
}
public static void Test(ref int x)
{
x = 2;
}
Upvotes: 1