To be clear, I want the behavior of a pointer-to-a-pointer, and the purpose of this question is to generate clean, readable code.
I have some code that contains conditions checking the result of multiple Dictionary.TryGetValue calls. It would be cleaner if it could retrieve all of the required objects with a single call, so I wanted to write an extension that will allow me to do the following:
Dictionary<string, string> myDictionary; // Initialized somewhere
string x, y, z;
bool foundAllEntries = myDictionary.TryGetValues({"xvalue", out x}, {"yvalue", out y},
{"zvalue", out z});
if (foundAllEntries)
; // Do something with x, y, and z
However, I can't figure out a way to pass the extension method references to the objects that will hold the output. This seems like something that should be very basic.
How can I store a reference to a local reference in an object?
Please note that this question is not asking for alternative approaches to implementing the TryGetValues function. There are many ways I can make this 'work,' but none generate code as clean as the approach I'm trying to take.
This seems like something that should be very basic.
Not only it isn't basic, it's outright impossible: there is no way to decorate a data type with ref or out - these modifiers are applicable exclusively to formal method parameters. In other words, there is no such thing as a "reference variable" or an "output variable"; there are only "reference parameters" and "output parameters" in the language.
Moreover, you cannot pass output or by reference parameters as part of a variable-length argument list (i.e. the params portion) so that approach wouldn't work either.
There are many ways I can make this 'work,' but none generate code as clean as the approach I'm trying to take.
Curiously, the above does not mean that you cannot implement the scheme that you are trying to implement, leaving the code nearly as clean as your original one if you apply the Proxy Design Pattern. The trick is to chain method calls, and provide an implicit conversion operator for the result, like this:
class MyMap {
internal IDictionary<string,string> dict = ...
public ItemGetterResult TryGetValues {
get {
return new ItemGetterResult(this, true);
}
}
}
class ItemGetterResult {
private readonly MyMap map;
private bool IsSuccessful {get;set;}
internal ItemGetterResult(MyMap theMap, bool successFlag) {
map = theMap;
IsSuccessful = successFlag;
}
public static implicit operator bool(ItemGetterResult r) {
return r.IsSuccessful;
}
public ItemGetterResult Get(string key, out string val) {
return new ItemGetterResult(
map
, this.IsSuccessful && map.dict.TryGetValue(key, out val)
);
}
}
Now the call looks like this:
bool foundAllEntries = myDictionary.TryGetValues
.Get("xvalue", out x)
.Get("yvalue", out y)
.Get("zvalue", out z);
You can create a mutable Reference type:
public class Reference<T>
{
public T Value;
}
/* declaration */
bool TryGetValues(
this Dictionary<K,V> dict,
params Tuple<K, Reference<V>>[] requests)
/* call site */
var x = new Reference<string>();
var y = new Reference<string>();
var z = new Reference<string>();
bool foundAllEntries = myDictionary.TryGetValues(
Tuple.Create("xvalue", x),
Tuple.Create("yvalue", y),
Tuple.Create("zvalue", z));
Related
I am new to C#. I am trying to implement a Dictionary in C# whose Java-equivalent is:
HashMap<string, Variable<?>> dictionary
Here is the detailed Java version of what I'm trying to do: Java how to manage user-defined variables
In C# so far I have something like this:
interface IVariable { }
public class Variable<T> : IVariable
{
public T myValue { get; set; }
}
Dictionary<string, IVariable> vars = new Dictionary<string, IVariable>();
Then I try to do this:
Variable<int> age = new Variable<int>();
age.myValue = 12;
vars.Add("age", age);
IVariable theVar;
if (vars.TryGetValue("age", out theVar) {
Console.WriteLine("fetched age is " + theVar.myValue);
}
I run into trouble in the last line because the compiler doesn't recognize the myValue member of a theVar because it is an IVariable.
In this simple example maybe I could declare theVar to be a Variable<int> instead of an IVariable but I haven't tried it because it would require a priori knowledge about what kind of variable I'm fetching from the dictionary and I might not always have that knowledge.
I wouldn't mind if myValue were an inherited/abstract property (if there is such a thing), since every Variable will have a property named myValue (each will differ in type but not in name). In that case I guess I could make IVariable an abstract class rather than an interface, but then I still run into trouble as far as what to put for the type of myValue.
Could I do a cast of theVar into something using as by first checking its type with is? I'm not sure if that would work or is even possible.
I've looked at these posts for guidance (especially the second one):
Wildcard equivalent in C# generics
C# Generics: wildcards
However, my situation is still slightly different than the second example above because that example has an abstract method that is returning a void whereas I wish to have my variables return non-void generic values.
Thanks for any help.
C# has dynamic. You can create Dictionary<string, dynamic>
Or you can use object (boxing/unboxing) Dictionary<string, object>
Or you can get generic type from class
class MyClass<TDicValue>
{
Dictionary<strint, TDicValue> myDictionary;
}
I had this same problem where I had 20 slightly different types and I had to keep dictionaries on. I wanted to organize them in a list.
The problem was the same, selecting the right kind from the list with reflection or strings lacked the ability to provide a type to return to. #skrilmps answer is correct, but packing and and unpacking was at best unreliable without a lot (metric ton) of ugly messy code.
While unity does support dynamics in 2020, this doesn't exactly work with what i am doing unless I make like everything dynamic safe and that's shamble coding, not extensible or maintainable, and just sounds like a general nightmare.
I personally feel that I am an inadequate programmer after years of trying to learn and still not having my efforts provide a productive return or product of note, so i cannot claim the answer being mine, but in my research on the proper solution to this problem i found this: https://www.youtube.com/watch?v=A7qwuFnyIpM
In here he says basically if you add an interface to your similar classes that are intended for use in a variety of different lists, that you can instead make a list of that type of interface. I would assume dictionary as well, and then you can add any kind of class implementing this interface to this singular interface type defined list.
I tried using boxing/unboxing and came up with this solution. It appears to work... so far. But it doesn't seem very safe.
public interface Variable
{
object getValue();
void setValue(object value);
Type myType();
}
public class Variable<T>: Variable
{
private T myValue;
public object getValue()
{
return myValue;
}
public void setValue(object value)
{
myValue = (T)value;
}
public Type myType() { return myValue.GetType(); }
}
Dictionary<string, Variable> vars = new Dictionary<string, Variable>();
Variable<int> age = new Variable<int>();
age.setValue(21);
vars.Add("age", age);
Variable theAgeVar;
vars.TryGetValue("age", out theAgeVar);
Console.WriteLine("age = " + theAgeVar.getValue());
Variable<double> height = new Variable<double>();
height.setValue(5.9);
Variable theHeightVar;
vars.TryGetValue("age", out theHeightVar);
Debug.Log("height = " + theHeightVar.getValue());
This prints:
age = 21
height = 5.9
One thing I do not like is that I had to make the return type of getValue() be an object. If I wanted myValue (which is of type T) to implement IComparable, for instance, then this information is lost when the boxing happens and the caller receives an object.
// The following should resolve the boxing problem and now is totally generic:
public interface IVariable<T>
{
T GetContent();
void SetContent(T value);
Type GetDataType();
}
public class Variable<T> : IVariable
{
private T content;
public T GetContent()
{
return content;
}
public void SetContent(T value)
{
content = value;
}
public Type GetDataType() { return GetType(); }
}
Dictionary<string, Variable<T>> variables = new Dictionary<string, Variable<T>>();
What is the best way of passing both a List<T> and a bool as the returning value of a method? Right now I have this custom class called BoolList acting like a container but I was wondering if there is a better and/or more elegant way of doing it.
Why not use a tuple?
http://www.dotnetperls.com/tuple
http://msdn.microsoft.com/en-us/library/dd268536.aspx
Then you have a type-safe container without having to create a class.
private Tuple<List<int>, bool> myMethod()
{
var myList = new List<int>();
var myBool = true;
return new Tuple<List<int>, bool>(myList, myBool);
}
You can use Tuple<List<T>, bool>
public Tuple<List<string>, bool> MethodName()
{
return Tuple.Create(new List<string>(), true);
}
or make the List<T> out parameter and return bool as normal one (like TryParse methods do)
public bool MethodName(out List<string> results)
{
results = new List<string>();
return true;
}
As already mentioned here, you can use a tuple and that is a good solution. The only drawback being that you refer to the items in the tuple with the non-informative names Item1, Item2... If you are going to be returning the same types often or you will be passing the result around where descriptive properties improve readability, then the other (old-fashioned) way is to have a class (or struct as described further down in this answer) with the return types as properties and return an instance of the class. For example a class definition could be local to your current class.
public class EmployeeSearchResult
{
public List<Employee> Employees{get;set;}
public bool Success{get;set;}
}
private EmployeeSearchResult Search()
{
var employeeSearchResult = new EmployeeSearchResult();
employeeSearchResult.Employees = new List<Employee>();
employeeSearchResult.SearchSuccess = true;
return employeeSearchResult;
}
Since the return is often small and lightweight with a short lifespan a struct may be a better option than a class. However, be aware of when a struct is appropriate - as per msdn: -
√ CONSIDER defining a struct instead of a class if instances of the
type are small and commonly short-lived or are commonly embedded in
other objects.
X AVOID defining a struct unless the type has all of
the following characteristics:
It logically represents a single value, similar to primitive types (int, double, etc.).
It has an instance size under 16 bytes.
It is immutable.
It will not have to be boxed frequently.
First, excuse the rather funny name of my question. I'm no native speaker and it took me 10 minutes to express my thoughts in these few characters.
What I'm trying to do is to create a dictionary in C# that allows the value to be either an int, a string or a bool. What first had come to my mind was using generics, but as far as I know, I can only define one type as possible value-type, not "be one of those". Using object would also be possible, but boxing seems to be quite a performance-killer.
Is there any way to do this?
Here's a sample of what has come to my mind:
Dictionary<string, (string, int, bool)> foo = new Dictionary<string, (string, int, bool)>();
foo.Add("key1", "Hello, World!"); //Correct - Value is a string
foo.Add("key2", 37); //Correct - Value is an int
foo.Add("key3", true); //Correct - Value is a boolean
foo.Add("key4", new Foobar()); //Compiler error - Value is a Foobar
My ultimate goal is to provide a library for other developers. This feature should enable them to define "variables" during runtime and give them a type.
Edit://Firefox' about:config page has something very close to what I want to achieve
Why not create a fresh new class which implements the IDictionary and uses a Dictionary as a private variable.
Then, in the add methods, you can provide your own logic and fail accordingly
Sample code
public class MyDic : IDictionary<object, object>
{
private Dictionary<object, object> privateDic= new Dictionary<object,object>();
public void Add(object key, object value)
{
if (value.GetType() == typeof(string))
throw new ArgumentException();
privateDic.Add(key, value);
}
//Rest of the interface follows
}
I would suggest to:
Create a base type for your dictionary values e.g. MyDictionaryBaseType
Extend this basic type for each dictionary value type your have e.g. StringDictionryType : MyDictionaryBaseType, IntegerDictionryType : MyDictionaryBaseType...etc.
Create a generic dictionary type with MyDictionaryBaseType and limit the type to extend this base type.
This way you limit your dictionry to three specifed types
You can put the values into wrapper classs like this:
class Value
{
}
class TypedValue<T> : Value
{
public T Val;
}
class IntValue : TypedValue<int>
{
}
class StringValue : TypedValue<string>
{
}
class BoolValue : TypedValue<bool>
{
}
Dictionary<string,Value> foo;
foo.Add("key1", new StringValue{Val="Hello World!"});
Another possibility would be to use a Dictionary and do a runtime check for right or wrong types added. I don't think there is a solution without involving boxing.
What you are trying to accomplish isn't type-safe as it stands. For example, let's say you have such a dictionary:
var foo = new Dictionary<string, (string, int, bool)>();
var x = foo["key1"];
// What type is x? How could the compiler know?
One idea would be to devise a container class which can hold one-of either string, int, or bool.
public class StringIntBool {
private bool _isSet;
private bool _isString;
public bool IsString {
get { return _isString; }
}
// ...
private string _innerString;
public string InnerString {
get {
return _innerString;
}
set {
if (_isSet) {
throw new Exception("StringIntBool is already set");
}
_isSet = true;
_isString = true;
_innerString = value;
}
}
// etc...
}
This is quite ugly, and doesn't really give many benefits.
As an alternative, you could actually store all three values as objects, and then use a technique / library like Functional C# to perform pattern-matching, like many functional languages can.
object x = "str";
int res = x.Match()
.With<string>(s => s == "str" ? 10 : 20)
.With<int>(i => i)
.With<bool>(b => b ? 50 : 60)
.Return<int>();
This pattern of programming is actually pretty common in certain functional language. For example, in SML, you can define a datatype, and then pattern-match it as needed.
(* StringIntBool *)
datatype sib = SibString of string | SibInt of int | SibBool of bool
val x = (* some instance of sib *)
val y = case x of
SibString s => if s = "hello" then 50 else -50
| SibInt i => i
| SibBool b => if b then 10 else 20
I am trying to understand how to assign by "reference" to a class field in C#.
I have the following example to consider:
public class X
{
public X()
{
string example = "X";
new Y(ref example);
new Z(ref example);
System.Diagnostics.Debug.WriteLine(example);
}
}
public class Y
{
public Y( ref string example )
{
example += " (Updated By Y)";
}
}
public class Z
{
private string _Example;
public Z(ref string example)
{
this._Example = example;
this._Example += " (Updated By Z)";
}
}
var x = new X();
When running the above code the output is:
X (Updated By Y)
And not:
X (Updated By Y) (Updated By Z)
As I had hoped.
It seems that assigning a "ref parameter" to a field loses the reference.
Is there a way to keep hold of the reference when assigning to a field?
As others have noted, you cannot have a field of "ref to variable" type. However, just knowing that you cannot do it is probably unsatisfying; you probably also want to know first, why not, and second, how to get around this restriction.
The reason why is because there are only three possibilities:
1) Disallow fields of ref type
2) Allow unsafe fields of ref type
3) Do not use the temporary storage pool for local variables (aka "the stack")
Suppose we allowed fields of ref type. Then you could do
public ref int x;
void M()
{
int y = 123;
this.x = ref y;
}
and now y can be accessed after M completes. This means that either we're in case (2) -- accessing this.x will crash and die horribly because the storage for y no longer exists -- or we're in case (3), and the local y is stored on the garbage collected heap, not the temporary memory pool.
We like the optimization that local variables be stored on the temporary pool even if they are being passed by ref, and we hate the idea that you could leave a time bomb around that could make your program crash and die later. Therefore, option one it is: no ref fields.
Note that for local variables that are closed-over variables of anonymous functions we choose option (3); those local variables are not allocated out of the temporary pool.
Which then brings us to the second question: how do you get around it? If the reason you want a ref field is to make a getter and setter of another variable, that's perfectly legal:
sealed class Ref<T>
{
private readonly Func<T> getter;
private readonly Action<T> setter;
public Ref(Func<T> getter, Action<T> setter)
{
this.getter = getter;
this.setter = setter;
}
public T Value { get { return getter(); } set { setter(value); } }
}
...
Ref<int> x;
void M()
{
int y = 123;
x = new Ref<int>(()=>y, z=>{y=z;});
x.Value = 456;
Console.WriteLine(y); // 456 -- setting x.Value changes y.
}
And there you go. y is stored on the gc heap, and x is an object that has the ability to get and set y.
Note that the CLR does support ref locals and ref returning methods, though C# does not. Perhaps a hypothetical future version of C# will support these features; I have prototyped it and it works well. However, this is not real high on the priority list, so I wouldn't get my hopes up.
UPDATE: The feature mentioned in the paragraph above was finally implemented for real in C# 7. However, you still cannot store a ref in a field.
No. ref is purely a calling convention. You can't use it to qualify a field. In Z, _Example gets set to the value of the string reference passed in. You then assign a new string reference to it using +=. You never assign to example, so the ref has no effect.
The only work-around for what you want is to have a shared mutable wrapper object (an array or a hypothetical StringWrapper) that contains the reference (a string here). Generally, if you need this, you can find a larger mutable object for the classes to share.
public class StringWrapper
{
public string s;
public StringWrapper(string s)
{
this.s = s;
}
public string ToString()
{
return s;
}
}
public class X
{
public X()
{
StringWrapper example = new StringWrapper("X");
new Z(example)
System.Diagnostics.Debug.WriteLine( example );
}
}
public class Z
{
private StringWrapper _Example;
public Z( StringWrapper example )
{
this._Example = example;
this._Example.s += " (Updated By Z)";
}
}
You forgot to update the reference in the Z class:
public class Z {
private string _Example;
public Z(ref string example) {
example = this._Example += " (Updated By Z)";
}
}
Output: X (Updated By Y) (Updated By Z)
Point to keep in mind is that the += operator for a string calls the String.Concat() method. Which creates a new string object, it doesn't update the value of a string. String objects are immutable, the string class doesn't have any methods or fields that lets you change the value. Very different from the default behavior of a regular reference type.
So if you use a string method or operator, you always have to assign the return value back to a variable. This is pretty natural syntax, value types behave the same way. Your code would be very similar if you used an int instead of a string.
I've completed a OOP course assignment where I design and code a Complex Number class. For extra credit, I can do the following:
Add two complex numbers. The function will take one complex number object as a parameter and return a complex number object. When adding two complex numbers, the real part of the calling object is added to the real part of the complex number object passed as a parameter, and the imaginary part of the calling object is added to the imaginary part of the complex number object passed as a parameter.
Subtract two complex numbers. The
function will take one complex
number object as a parameter and
return a complex number object. When
subtracting two complex numbers, the
real part of the complex number
object passed as a parameter is
subtracted from the real part of the
calling object, and the imaginary
part of the complex number object
passed as a parameter is subtracted
from the imaginary part of the
calling object.
I have coded this up, and I used the this keyword to denote the current instance of the class, the code for my add method is below, and my subtract method looks similar:
public ComplexNumber Add(ComplexNumber c)
{
double realPartAdder = c.GetRealPart();
double complexPartAdder = c.GetComplexPart();
double realPartCaller = this.GetRealPart();
double complexPartCaller = this.GetComplexPart();
double finalRealPart = realPartCaller + realPartAdder;
double finalComplexPart = complexPartCaller + complexPartAdder;
ComplexNumber summedComplex = new ComplexNumber(finalRealPart, finalComplexPart);
return summedComplex;
}
My question is: Did I do this correctly and with good style? (using the this keyword)?
The use of the this keyword can be discussed, but it usually boils down to personal taste. In this case, while being redundant from a technical point of view, I personally think it adds clarity, so I would use it as well.
Use of the redundant this. is encouraged by the Microsoft coding standards as embodied in the StyleCop tool.
You can also to overload math operators, just like:
public static ComplexNumber operator +(ComplexNumber c1, ComplexNumber c2)
Since you're now learning C# and asking about style, I'm going to show you several things that are wrong with the code you posted along with reasons.
Edit: I only responded to this because it looks like you actually working to figure this stuff out. Since that's the type of people I prefer to work with, I'm more critical simply because I hope it helps you get somewhere better as a result. :)
Structure name
ComplexNumber is unnecessarily long. Note that none of Single, Double, Int32, Int64, etc. have Number in the name. This suggests Complex as a more appropriate name.
Complex matches the naming already established in the .NET Framework.
Real and imaginary components
GetRealPart() and GetComplexPart() should be get-only properties instead of methods.
GetComplexPart() is misnamed because it is actually returning the imaginary part.
Since the .NET framework already has a Complex structure, you shouldn't reinvent the naming. Therefore, unless you are in a position to redefine Framework conventions, the properties must be named Real and Imaginary.
Operations
If you look at existing examples like System.Windows.Vector, you see that math operations are implemented by providing a static method and an operator:
public static Point Add(Vector vector, Point point);
public static Point operator+(Vector vector, Point point);
Not surprisingly, this convention carried over to the System.Numerics.Complex structure:
public static Complex Add(Complex left, Complex right);
public static Complex operator +(Complex left, Complex right);
Summary
The result is clean, easy to verify, and behaves as everyone expects. The this keyword doesn't/can't appear because the methods are static.
public static Complex Add(Complex left, Complex right)
{
return new Complex(left.Real + right.Real, left.Imaginary + right.Imaginary);
}
public static Complex operator +(Complex left, Complex right)
{
return new Complex(left.Real + right.Real, left.Imaginary + right.Imaginary);
}
I use this keyword only for variables and when there's an argument that has the same name as the private variable. i.e.
private String firstname;
public SetName(String firstname)
{
this.firstname = firstname;
}
I would say yes, it looks correct and easy to read. But isn't this something your TA should answer?
double realPartCaller = this.GetRealPart();
Even if you omit this from GetRealPart() it should still be okay. But the use of this makes it quite easy to read and understand when it comes to maintainer.
double realPartCaller = this.GetRealPart(); ==> bit more readable IMHO
double realPartCaller = GetRealPart();
I find myself more and more using the this keyword for both methods and properties on the current instance, as I feel it increases readability and maintainability. this is especially useful if your class also has static methods and/or properties, on which you of course can not use the this keyword, as these are not related to the current instance. By using this, you clearly see the difference.
To bring it even further, you should consider using the class name as a qualifier for static methods and properties, even within the class itself.
Just to add completeness to the answers - there is one case when the this keyword is mandatory. That's when you have a local variable (or a method parameter) that has the same name as a class member. In this case writing it without this will access the local variable and with this will set the class member. To illustrate:
class MyClass
{
public int SomeVariable;
public void SomeMethod()
{
int SomeVariable;
SomeVariable = 4; // This assigns the local variable.
this.SomeVariable = 6; // This assigns the class member.
}
}
A couple things that follow from this:
Always avoid giving local variables the same name as class members (I admit, I don't always follow this myself);
Writing this in front of all member accesses acts like a safeguard. If you write a piece of code without it, and then later introduce a local variable with the same name and type as a class member, your code will still compile just fine, but will do something completely different (and probably wrong).
One instance though where I use the same names for method parameters as for class members is in constructors. I often write it like this:
class MyClass
{
public int VariableA;
public string VariableB;
public MyClass(int VariableA, string VariableB)
{
this.VariableA = VariableA;
this.VariableB = VariableB;
}
}
In my opinion this makes the constructor clearer, because you immediately understand which parameter sets which class member.
Usage of this keyword seems fine.
Though I believe for a class like Complex you should store the real and complex part as int properties and use them in the method, rather than using the methods GetRealPart() and GetComplexPart()
I would do it this way:
class ComplexNumber
{
public int RealPart { get; set; }
public int ComplexPart { get; set; }
public ComplexNumber(int real, int complex)
{
this.RealPart = real;
this.ComplexPart = complex;
}
public ComplexNumber Add(ComplexNumber c)
{
return new ComplexNumber(this.RealPart + c.RealPart, this.ComplexPart + c.ComplexPart);
}
}
The following is a scenario where this MUST be used, otherwise, the parameter and not the class member is considered for both LHS and RHS of the assignment.
public ComplexNumber(int RealPart, int ComplexPart)
{
RealPart = RealPart; // class member will not be assigned value of RealPart
ComplexPart = ComplexPart;
}
If you follow the naming conventions, using this is rearlly neded:
class MyClass
{
public int _variableA;
public string _variableB;
public MyClass(int variableA, string variableB)
{
_variableA = variableA;
_variableB = variableB;
}
}