Advice for how best to adapt a Python habit to C#
(This is code for a Game of Life board's
Populate
method, that aims to create a 2D array of tiles based on a percentage living rate, or entered pattern)
The way I used to do this in Python is as shown, I would pass a float into a method, but in the method I'd check first that the float wasn't a string, in which case I'd act differently. I could obviously do this by setting percentage as a var or object, and checking it can be cast to different types, but I'm curious to know what's best practice here. Can I do something with overloads? Optional parameters? I'm still very new to this.21 Replies
(oh also tileState is an int for other reasons)
Well, in C#, a float cannot be a string
So you might need a second parameter, for example
An enum perhaps
Or, indeed, a method overload
One that takes
float percentage
and other that takes float percentage, SomethingType somethingType
With
Although it seems you wouldn't need that percentage
parameter for the second methodideally, i would only need to pass a percentage in the case that the enum is Percentage, rather than Checkerboard etc
since it isnt used in any other case
A float cannot be an enum
An enum cannot be a float
A float cannot be a string...
you get the idea
yeye
i guess i can just pass in the enum and then an optional parameter for percentage which i only use if passed in
it just feels ungainly to have to pass in an enum even if percentage is given, or have to pass in a percentage even if the enum is Checkerboard etc
You can use overloads instead
wait theres a kind of method that acts differently on different types, could I have the method work differently on a string for the type of populate, and a float for the percentage?
i forget what it was called
Parametric polymorphism?
scary lol
overloads or like this
i could go find it,,, it might have been a class whose instances worked differently based on kind, so might be completely irrelevant
switch on Kind
ignore the float if kind is not Float
that's the best data oriented way to do it
this seems good, since theres a lot in the method before i reach the point where the overload is important, is there a way to not have the whole method twice?
An optional prameter ig
valid
are there overloads that can call each other?
i guess,,, thats just calling the method from one version of itself
Yes, you can call one method from another method
lastly, if im calling the Board's Populate method from outside it, where best do i define the enum to be used inside and outside it? just in the namespace i guess?
i might just not understand scope right here
Wherever, could be a whole separate file
ok the enum definitely makes this feel a lot neater, even with the sorta stray null float