Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convention while using Helper Casting Functions

I recently began to start using functions to make casting easier on my fingers for one instance I had something like this

((Dictionary<string,string>)value).Add(foo);

and converted it to a tiny little helper function so I can do this

ToDictionary(value).Add(foo);

Is this against the coding standards?

Also, what about simpler examples? For example in my scripting engine I've considered making things like this

((StringVariable)arg).Value="foo";

be

ToStringVar(arg).Value="foo";

I really just dislike how inorder to cast a value and instantly get a property from it you must enclose it in double parentheses. I have a feeling the last one is much worse than the first one though

like image 802
Earlz Avatar asked Jun 14 '26 17:06

Earlz


2 Answers

Ignoring for a moment that you may actually need to do this casting - which I personally doubt - if you really just want to "save your fingers", you can use a using statement to shorten the name of your generic types.

At the top of your file, with all the other usings:

using ShorterType = Dictionary<string, Dictionary<int, List<Dictionary<OtherType, ThisIsRidiculous>>>>;
like image 176
Tesserex Avatar answered Jun 16 '26 06:06

Tesserex


I don't think so. You've also done something nice in that it's a bit easier to read and see what's going on. Glib (in C) provides casting macros for their classes, so this isn't a new concept. Just don't go overkill trying to save your fingers.

like image 28
NG. Avatar answered Jun 16 '26 08:06

NG.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!