Poll of the Day > Cool function I wrote

Topic List
Page List: 1
Yellow
10/04/18 5:30:34 AM
#1:


So, I'm making my own Windows Forms/Qt equivalent in MonoGame (a library pretty much meant for games only), and I just got done making a object-to-child-class code generator. Basically how Windows Forms adds new windows as classes to your code. I can't really explain it well, but it does this.

// My 'Animal' test class
....public class Animal
....{
........public Animal()
........{
........
........}
........public Animal(String name)
........{
............this.species = name;
........}
........public Animal(String name, int height)
........{
............this.species = name;
............this.height = height;
........}
........
........public string species;
........public int height;
....}

Animal goat = new Animal("Goat", 20);
String cs_file = CSCreator.SerializeToCS(goat, "Goat");
System.IO.File.WriteAllText(@"WriteText.txt", cs_file);


This will take goat and write to a CS file a class that inherits Animal, preserving all the fields as they were.

// All auto-generated
using DownUnder.Content.Utilities;
using DownUnder.Content.UI;

namespace DownUnder.Content.Utilities
{
....public class Goat : Animal
....{
........public Goat() : base() { species = "Goat"; height = 20; }
........public Goat(System.String name) : base(name) { name = "Goat"; height = 20; }
........public Goat(System.String name, System.Int32 height) : base(name, height) { name = "Goat"; height = 20; }

....}
}


//...
// After adding in the generated code
Goat my_goat = new Goat();
Debug.WriteLine("" + my_goat.species);


Goat

I feel like MS has made something like this and gave us access to it, (idk why else you would have such a functional Reflection system) and I just wrote this for no reason, but oh well. Anyone feel free to use my code without credit. Be careful though, if I recall @Judgmenl said I'm a huge idiot that doesn't know anything about programming.

Source
https://pastebin.com/WDLygCRs

@Sahuagin
... Copied to Clipboard!
Lokarin
10/04/18 5:32:55 AM
#2:


Wanna go into insane science?

You can express every animal in history from a common ancestor (parent group) by a process of simply adding new or changing existing variables to form a gigantic phylogenetic tree
---
"Salt cures Everything!"
My YouTube: https://www.youtube.com/user/Nirakolov/videos
... Copied to Clipboard!
Yellow
10/04/18 5:41:06 AM
#3:


Lokarin posted...
Wanna go into insane science?

You can express every animal in history from a common ancestor (parent group) by a process of simply adding new or changing existing variables to form a gigantic phylogenetic tree

Sure, but you would have to have the ability to remove fields too.
... Copied to Clipboard!
Judgmenl
10/04/18 6:09:12 AM
#4:


Man I am so proud of you bragging about your sick programming skills with no professional programming experience on a message board on the internet.
---
Judge, Nostalgia is a hell of a drug.
You're a regular Jack Kerouac
... Copied to Clipboard!
Ranzoh
10/04/18 7:28:47 AM
#5:


Goats are popular with gay kidnaps. They make cool friends on this site the majority of the site.
... Copied to Clipboard!
SunWuKung420
10/04/18 8:21:04 AM
#6:


Judgmenl posted...
Man I am so proud of you bragging about your sick programming skills with no professional programming experience on a message board on the internet.


Are you mad you paid to learn something anyone can learn on their own for free?
---
"Men have to restrain themselves around other men to avoid an outright punch out"- Kyuubi4269 9/17/18
PSN - SunWuKung420
... Copied to Clipboard!
Judgmenl
10/04/18 9:08:10 AM
#7:


I didn't pay anything, the state did.

I also have zero debt, am extremely happy with my career (best part of my life tbh) and I do not have to worry about money / will never have to worry about money for the rest of my life.
---
Judge, Nostalgia is a hell of a drug.
You're a regular Jack Kerouac
... Copied to Clipboard!
Yellow
10/04/18 1:00:24 PM
#8:


Ranzoh posted...
Goats are popular with gay kidnaps. They make cool friends on this site the majority of the site.

U R high.
... Copied to Clipboard!
Yellow
10/04/18 1:06:04 PM
#9:


Judgmenl posted...
Man I am so proud of you bragging about your sick programming skills with no professional programming experience on a message board on the internet.

I know right
... Copied to Clipboard!
Black_Crusher
10/04/18 1:08:19 PM
#10:


Judgmenl posted...
Man I am so proud of you bragging about your sick programming skills with no professional programming experience on a message board on the internet.

I have some, and this was pretty cool.
---
... Copied to Clipboard!
Yellow
10/04/18 1:14:39 PM
#11:


Actually, no one should use this, It doesn't account for fields that aren't System.Single or string yet, and it doesn't really do indentation well yet either.
... Copied to Clipboard!
Sahuagin
10/04/18 11:03:29 PM
#12:


not sure what I should say. some random tips:

- look up StringBuilder
- your function doesn't need to be generic, you could just pass a Type as a parameter
- consider making it an instance of a class rather than a static class, and then push some data up into fields rather than passing arguments
- you don't need to use ref parameters, that's just if you would want to send a value back up from the function into the variable
- not that important, but should use C# names instead of .NET names for things like string VS String
---
... Copied to Clipboard!
Kungfu Kenobi
10/04/18 11:24:35 PM
#13:


TIL the GameFAQs Code tag doesn't preserve indentation.
---
This album is not available to the public.
Even if it were, you wouldn't wanna listen to it!
... Copied to Clipboard!
GanglyKhan
10/05/18 12:32:24 AM
#14:


I think programming is awesome. It really is an entirely different language.
... Copied to Clipboard!
jramirez23
10/05/18 12:36:39 AM
#15:


I don't really understand what is going on there but it sounds interesting.
---
I consider it completely unimportant who in the party will vote, or how; but what is extraordinarily important is this who will count the votes, and how.
... Copied to Clipboard!
GanonsSpirit
10/05/18 1:22:37 AM
#16:


Yeah, well, BTB and I wrote a script that I eventually just used to watch a random porn video when provided with a tag.
---
https://imgur.com/tsQUpxC Thanks, Nade Duck!
[[[[[[[[[[[[[[[|||||||||||||]]]]]]]]]]]]]]]]
... Copied to Clipboard!
Yellow
10/05/18 1:43:28 AM
#17:


Sahuagin posted...
not sure what I should say. some random tips:

Idk, I'll stop tagging you for random coding things. I just think your advice is very valuable.

- look up StringBuilder
Noted

- your function doesn't need to be generic, you could just pass a Type as a parameter
Well, the idea is that it would take an existing object and turn it into a class, I don't see the point in passing the type independently when I can pass the type and the object at once.

I could probably just use 'object' instead of 'T' and get the same results, removing the generic.

- consider making it an instance of a class rather than a static class, and then push some data up into fields rather than passing arguments
Currently, that seems like overcomplicating things, I only pass the name of the new object atm. If it gets more complicated than that, I'll keep this in mind.

- you don't need to use ref parameters, that's just if you would want to send a value back up from the function into the variable
Dang, I feel like half the time in C# I don't need to use ref as intended, since most objects just pass references anyway. Whenever I do use ref, I just feel like I'd rather be safe than sorry, or at the very least remind myself the object is supposed to be modified. (The ref parameter actually modifies the list)

- not that important, but should use C# names instead of .NET names for things like string VS String
Noted and fixed
... Copied to Clipboard!
Magus 10
10/05/18 1:51:08 AM
#18:


Yellow posted...
I feel like half the time in C# I don't need to use ref as intended, since most objects just pass references anyway.


You should never use ref unless you have a very good reason why (which 90% of the time is PInvoke, and the other 10% can probably be done a better way with tuples or something; edit: actually that's more likely the solution for out params, but I can't think of anything else for the other 10%).
---
Internet = Tube0 + Tube1X + Tube2X^2/2! + Tube3X^3/3! + Tube4X^4/4! + ...
... Copied to Clipboard!
Sahuagin
10/05/18 2:09:23 AM
#19:


Yellow posted...
Well, the idea is that it would take an existing object and turn it into a class, I don't see the point in passing the type independently when I can pass the type and the object at once.

right k, in that case you could just call .GetType() on the object. generic methods are definitely useful, but generics are a complexity that is often better removed when possible. basically you would make it generic if you needed it to be strongly typed, so if there was a return value or property somewhere that you wanted to be type T so that outside users would get back the type they're working with and not something like object.

a lot of the time too, you might have an overload that is generic on T, but then just passes typeof(T) to the real method that works on the Type object. the generic overload can be easier to use if the external context has a type parameter, and then the caller doesn't have to manually type typeof(T).

(I very often end up doing things this last way. the problem is that you can get a Type object from a generic T very easily, but if in the context you're working in you don't have a generic T, and you just have a Type object, you can't turn it into a generic T without some reflection. so usually the method that does all the work takes a Type object, and the generic method is just for convenience.)

Yellow posted...
I feel like half the time in C# I don't need to use ref as intended, since most objects just pass references anyway.

everything is passed by value, including object references. think of the ref keyword as meaning "in/out".

regular parameter: the value passed is received by the method. if the method changes the value of the parameter, nothing is changed "outside" of the method (the original variable that the value came from is not changed).

out parameter: you can't even pass in a value, you can only (and must) assign a value to the parameter within the method which then comes out of the method into a target variable. (new in C# 7 you can now use out var to create a variable inline, rather than define a variable on a separate line.)

ref parameter: you can pass in a value, *and* the parameter is linked to what was passed in such that if you modify the parameter, you modify the external variable. (the value of the variable, not the underlying object. so a ref list parameter means that you could pass back a different list than the one that was passed in (or you could pass back null). you don't need ref in order to manipulate the list, that already happens just by having a reference to the list).

in parameter (new in C# 7): you can pass in a value, but the method cannot change the parameter. basically a readonly parameter.
---
... Copied to Clipboard!
Sahuagin
10/05/18 2:22:33 AM
#20:


Magus 10 posted...
You should never use ref unless you have a very good reason why (which 90% of the time is PInvoke, and the other 10% can probably be done a better way with tuples or something; edit: actually that's more likely the solution for out params, but I can't think of anything else for the other 10%).


one use for ref would be maybe if you had a counter that you wanted to pass between methods. then you can share the counter between a bunch of methods and increment it in any one of them. but then you can just put it in an object, too, which is better, so it's not super useful.

there are definitely some good uses for out parameters though, especially now that they aren't so clumsy in C# 7 with out var.

the standard example is something like:

if (!int.TryParse(someText, out var intValue))
...return;

// do something with intValue

---
... Copied to Clipboard!
Magus 10
10/05/18 2:35:08 AM
#21:


Sahuagin posted...
one use for ref would be maybe if you had a counter that you wanted to pass between methods. then you can share the counter between a bunch of methods and increment it in any one of them. but then you can just put it in an object, too, which is better, so it's not super useful.


Yeah, I'm not sure I'd really want to pass around state like that specifically.

I suppose the Interlocked methods are one example where it's pretty necessary, but I don't think most people are going to need to be implementing that particular set of methods.

Sahuagin posted...
the standard example is something like:

if (!int.TryParse(someText, out var intValue))
...return;

// do something with intValue


Yeah, multiple returns is the scenario I was thinking about with tuples being another option, although I suppose in the case where you're checking an error return value then out params are probably a little easier to use.
---
Internet = Tube0 + Tube1X + Tube2X^2/2! + Tube3X^3/3! + Tube4X^4/4! + ...
... Copied to Clipboard!
Sahuagin
10/05/18 11:25:01 AM
#22:


checking some of my code, one place I use ref is on string validation

bool ValidateAndClean(ref string pString) {
...
}


the bool return value indicates whether the string changed, and the string changes to a different string if it was "messy" (whatever that means in the context of the method)

Magus 10 posted...
Yeah, multiple returns is the scenario I was thinking about with tuples being another option, although I suppose in the case where you're checking an error return value then out params are probably a little easier to use.

another scenario is method chaining. if you want to return values while method chaining you have to use out parameters. I have a tree control where I build the parts of the tree in a method chain:


treeControl
.BuildLayers()
.AddLayer<T1, T2>(t2 => t2.Parent, t1 => t1.Children, out var layer1)
.AddLeafLayer<T2>(out var layer2);

// do stuff with layer1 and layer2


It's maybe a bit overkill, but I just wrote a method that allows me specifically to assign in a method chain, which allows me to avoid a starting variable at the top.


// generic extension method on object
T AssignTo<T>(
...this T pValue,
...out T pTarget
) =>
...pTarget = pValue;


turns this:


var myValue =
___methodChainStart
___.DoOneThing()
___.DoSomething()
___.ThenDoSomethingElse()
___.Select(x => x.SomeProperty);

// do something else with myValue

to this:

methodChainStart
.DoOneThing()
.DoSomething()
.ThenDoSomethingElse()
.Select(x => x.SomeProperty)
.AssignTo(out var myValue);

// do something else with myValue


it's not a huge difference, but it reads a lot nicer since the assignment is now where the actual value is instead of at the opposite end

also with TryParse, I actually clean it up so that I can write this:

if (someText.IsNot<int>(out var intValue))
...return;

// make use of intValue

---
... Copied to Clipboard!
Yellow
10/07/18 3:05:33 AM
#23:


The usefulness of our ref and in are lost on me currently. I will copy and paste this topic into a text file and read it before this topic purges. Although, Sahuagin you're using ref in the one case where you need to, since strings automatically copy themselves when passed, I noticed that.

It's interesting, eventually I should be able to do everything XMLSerializer does. I just have to chip through all the fringe cases.

I wonder if Mono wants this? I doubt it. I added decent parent/child window functionality too. Maybe MonoGame.Extended wants my work. Idk, I feel like open source people are too fickle sometimes.

I threw a class I actually want to use with it at it. It's a UI layout. All unsupported types are 'error'.

(Indentation not in yet)
using DownUnder.Content.Utilities;
using System.Collections.Generic;
using DownUnder.Content.UI;

// Sections of this code are autogenerated, changes made to sections
// between /*GeneratedCodeStart*/ and /*GeneratedCodeEnd*/ will
// not be preserved if the object is editted in DownUnder.UIEditor.
namespace DownUnder.Content.Utilities
{
public class LayoutGeneric : Layout
{
public LayoutGeneric() : base() {widgets = new List<Widget>(){new TaskBar(){drop_downs = new List<DropDown>(){new DropDown(){top_button = new PushButton(){label = new Label(){_area = error,outline_on_mouseover = error,outline_thickness = 3,_draw_outline = error,_color = error,_hovered_color = error,_text = "File",_text_color = error,_hovered_text_color = error,changing_color = new ChangingValue`1(){interpolation = error,transition_speed = 0.05f},changing_text_color = new ChangingValue`1(){interpolation = error,transition_speed = 0.05f},change_color_on_mouseover = error,d_update_area = null,d_click_action = null},spacing = 15,_area = error,outline_on_mouseover = error,outline_thickness = 3,_draw_outline = error,_color = error,_hovered_color = error,_text = "",_text_color = error,_hovered_text_color = error,changing_color = new ChangingValue`1(){interpolation = error,transition_speed = 0.05f},changing_text_color = new...
... Copied to Clipboard!
Sahuagin
10/07/18 1:51:05 PM
#24:


Yellow posted...
The usefulness of our ref and in are lost on me currently. I will copy and paste this topic into a text file and read it before this topic purges. Although, Sahuagin you're using ref in the one case where you need to, since strings automatically copy themselves when passed, I noticed that.

ref in the ValidateAndClean method allows me to get a different string back than the one I passed in. I use it for validating phone numbers and things like that. so maybe the user typed a super messy string "1 11 - 4 3 2 1 ". I scan it just for numeric digits and make sure there are 7 of them, and then return the cleaned string which includes a hyphen "111-4321". using the ref parameter, your external variable can be modified by the function, allowing you to get back a different string.

var phoneNumber = PhoneNumberBox.Text; // "1 11 - 4 3 2 1 "
ValidateAndClean(ref phoneNumber); "111-4321"

not sure if you know this already but it's worth explaining. in C# there are value types and reference types. when you say int x = 5;, since int is a value type, you are creating an int sized space of memory and placing an int sized 5 value into that memory.

but strings and objects aren't value types they are reference types. when you say string str = "this is a string"; you are allocating a <string length> chunk of memory off to the side, storing the string in it, but then for the variable you are allocating a memory address sized space of memory (32 or 64 bits), and storing the memory address of the chunk of memory where the string lives into the variable. when you pass a string as a parameter, you are passing the memory address by value. when you use a ref string parameter, you are saying that a value might come up out of the function back into my variable and overwrite the memory address in my string variable with a different memory address (that points at a different string than before).

the same is true for objects. so a ref List<T> parameter means that you can get back a different List<T> memory address than the one you passed in, allowing the function to overwrite the memory address you have on the outside, changing the List<T> that you're working on to a different one. (the old list still exists in memory, you just lose that one reference you had to it. once all references to an object are gone, it is free to be cleaned up by the garbage collector.)

(also a technical thing with strings is that there is "string interning". so if you say string str1 = "asdf"; string str2 = "asdf";, the space for "asdf" is only created once rather than duplicating the space, and both variables hold the same memory address.)
---
... Copied to Clipboard!
Yellow
10/11/18 5:07:01 AM
#25:


I get it now. That is bizarre and clunky, but it does make sense. It isn't a parallel to C++ pointers like I thought it was.

https://pastebin.com/STWDxups

This is currently where I'm at, objects create nested objects recursively, lists work, I'm working on multi-dimensional arrays atm.

Something neat is that this generates code in the release build, complete with object and class names. I wonder if I could attach this program to another and decompile objects from it.

(haven't fixed the refs yet)
https://pastebin.com/WDLygCRs
... Copied to Clipboard!
Sahuagin
10/11/18 10:05:02 PM
#26:


Yellow posted...
It isn't a parallel to C++ pointers like I thought it was.

it is, I think. (I'm not a huge expert on C++ and haven't used it in a long time so I could get something wrong here.)

using ref/out basically adds a single level of indirection. so an int becomes an int "reference/pointer". or an object reference, which is already a "reference/pointer", gets a second level of indirection (a pointer to a pointer/reference to a reference). "passing by reference" basically means "add another level of indirection so that you can manipulate the source too". but a C# reference variable already is a reference, so passing it by reference just means you want to also possibly change the reference instead of the object. (tricky semantics where we're passing a reference by value, or passing a reference by reference, which is different from passing a value by value or by reference.)

it would work the same way in C++. in C++ if you want the function to possibly modify your Object, pass an Object* instead (or Object&). if you want it to possibly modify your Object*, pass an Object** instead.

in C#, you can't really have a value typed object, except with "structs" (which confusingly work nothing like C structs). a value-typed object would work like an int. in C++ saying Object o; allocates an Object sized chunk of memory *right there*. no pointer or anything, you have an object existing right there in the function. that's C++. to do that in C# you'd need a struct. (but you don't want big things to work like that anyway. only use structs for small things; basically they are user-primitives.)

(in C++ 'struct' means something like "exactly the same as class except with different default visibility (everything public by default)". in C# it means "this is a value type, not a reference type".)
---
... Copied to Clipboard!
Topic List
Page List: 1